I am having a lot of problems using formControlName on a custom component wrapping an mat-select.
Now it appears that my custom control cannot find the form group? Even though the custom element is nested under the formGroup.
I have a StackBlitz
But the problem comes in when I nest my custom component under the formGroup, all of the other controls can find the formGroup but my custom component doesn't seem to be able to.
<form novalidate [formGroup]="tenantForm">
<label for="Id">Id</label>: <input class="form-control" formControlName="id" id="Id" name="Id" />
<custom-component-with-mat-select formControlName="culture" id="Culture" name="Culture"></custom-component-with-mat-select>
</form>
In this example the Id field would work properly, but the Culture field complains about not being nested in a FormGroup?
Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).
How should a custom component work with reactive forms and form group?
My original problem was not remembering to import the ReactiveFormsModule.. Maybe I'm forgetting to import something again?
Is this answer the designed way to accomplish this? Or am I missing a simplier solution??
Do I need to implement a control value accessor?? As explained here
just confused on the designed way to do this.
my component wraps angular material's mat-select, and I guess I'm also confused if I need to put attributes on the mat-select or have my component implement the control value accessor? nothing seems to be working.
I solved that problem using the parameter 'formControl' instead of 'formControlName' like this: input-date.compoenent.html
<p-calendar [formControl]="control"></p-calendar>
parent.component.html
<input-date [control]="formGroup.controls.date"></input-date>
Where control is an input of input-date.component:
@Input() control: FormControl;
Control formControlName
must be string value.
formControlName="animationType"
This working since animtationType
is string value here.
[formControlName]="'animationType'"
This is throwing error since Angular is evaluating the value of animationType
which is an array (defined in ts file)
formControlName="{{animationType}}"
This is failing as same reason as case 2
If you want to access the formControlName then use string value in ts ex :
** in ts **
public animationControl = "animation";
** in html **
<mat-select name="animationType" [formControlName]="'animationControl'"
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