mnu-nasir
mnu-nasir

Reputation: 1770

Dynamic child component under Parent component in Angular

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?

Upvotes: 0

Views: 45

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4820

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".

Upvotes: 1

Related Questions