3
votes

I have a custom form component in Angular2, using the ControlValueAccessor interface to integrate with the form in the parent component. This is working well for making the form dirty when the component gets touched.

However I can't find any way to get a field on the component, flagged as 'required', cause the parent form to become 'invalid' when it is not completed.

Is this even possible?

1
Welcome to Stack Overflow! Please review our SO Question Checklist to help you to ask a good question, and thus get a good answer.Joe C

1 Answers

2
votes

The custom form component can be marked with the required attribute .. so whatever value is bound to it via [(ngModel)] will be validated for that FormControl.

Does your custom component contain many input fields? If so then I think you'll need to look at custom validation for that component - see this example: Custom Component validation. The value returned from the validation logic will propagate to the parent and influence whether the parent form is valid or invalid.

If your custom component is say just a wrapper around a single input field, then you can just mark the custom component with required - so if it's invalid, the FormControl (for 'custom') will be marked as invalid (and therefore so will the parent form).

<app-custom-component name="custom" [(ngModel)]="model.customValue" required>
</app-custom-component>

where the template for the CustomComponet contains the <input /> field.