Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formControlName in a children component

Tags:

I would like to create a custom input component and reuse it in my forms, but I am hitting an issue with formGroup and formControlName.

// Form
<form [formGroup]='loginForm'>
  <custom-input [myFormControlName]='email'></custom-input>
</form>

// CustomInput Component's Template
<input formControlName='myFormControlName'>

The problem appears to be that formControlName is expecting to be used with a FormGroup directive and since I am using formControlName in a sub-component it doesn't find the formControlName.. Anyone knows how to work around that?

like image 570
Gabriel Avatar asked Sep 18 '17 11:09

Gabriel


People also ask

What is a child component?

A child component is the optional second level of an item type. Each child component is directly associated with the preceding level.

What is FormControlName?

The name corresponds to a key in the parent FormGroup or FormArray . Accepts a name as a string or a number. The name in the form of a string is useful for individual forms, while the numerical form allows for form controls to be bound to indices when iterating over controls in a FormArray . @Input('disabled')


2 Answers

Like @MassimoVariolo's article mentions, you can pass the form as an input to the child component.

Parent component html:

<child-component [form]="form"></child-component>

Child component ts file:

@Input() public form: FormGroup;

Child component html (you need the div with the formGroup, otherwise you'll get an error):

<div [formGroup]="form">
    <input formControlName="myFormControlName"> 
</div>
like image 57
Sofia Avatar answered Sep 17 '22 05:09

Sofia


You need to implement control value accessor in your child component read more here https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

like image 44
alexKhymenko Avatar answered Sep 18 '22 05:09

alexKhymenko