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?
A child component is the optional second level of an item type. Each child component is directly associated with the preceding level.
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')
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With