0

I have created a component where there is only a text field with some logic. Now I would like to use this component as a child component in another Parent component. Now I have three questions:

  1. How can I add the child component under the form group of the parent component
  2. How can I add the required validator whenever needed in any parent component.
  3. If the child component is used multiple times in a parent component how can I set the name field dynamically?
1
  • 1
    you can just pass it the form group directly via an input binding - the validators work the same because its part of the parent form group. it doesn't care that the child is used multiple times - you can create a name field via an array Commented Sep 6, 2021 at 8:25

1 Answer 1

1

Basically, you want your component to implement the ControlValueAccessor interface - this allows you to bind your component to either ngModel in template driven forms, or formControl (or formControlName) in reactive forms to be part of the form directly, and correctly react to changes in the form.

To also handle validators, your component will also have to implement Validator interface.

There are multiple comprehensive guides on how to correctly implement both interfaces so I won't cover that here - you can find them by googling "angular custom form control".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.