0
votes

I have a reactive form and I want to bind material input with a FormControl. When I use a raw html input like below, everything is ok:

<input type="text" formControlName="forContractor" />

but if I use mat-form-field like below, I get: "forContractor" highlighted with error message "Identifier 'forContractor' is not defined. The component declaration, template variable declarations, and element references do not contain such a memberng"

<mat-form-field appearance="outline">
  <mat-label>Contractor name</mat-label>
  <input matInput placeholder="Contractor name" [formControl]="forContractor" />
</mat-form-field>

component class:

addInvoiceForm = this.formBuilder.group({
    forContractor: [""],
});

I figured out, that if I create a property for this control and then assign it to the FormControl, a then bind this property with a template, problem dissappears. However, this looks odd, especially that I have 10 controls for this form. Is there a method to do this without creating a property for every control?

Odd solution:

forContractorControl = new FormControl("");

addInvoiceForm = this.formBuilder.group({
    forContractor: this.forContractorControl,
});

<mat-form-field appearance="outline">
  <mat-label>Contractor name</mat-label>
  <input matInput placeholder="Contractor name" [formControl]="forContractorControl" />
</mat-form-field>

1

1 Answers

0
votes

You need to put the mat-form-field in a <form></form> tag and then specify the group like this:

<form [formGroup]="addInvoiceForm" (ngSubmit)="onSubmit()">
 <mat-form-field appearance="outline">
   <mat-label>Contractor name</mat-label>
   <input matInput placeholder="Contractor name" formControlName="forContractorControl" />
 </mat-form-field>
</form>

I have done a lot of forms in angular material and ended up building my own library, you can check it out here ngx-mat-dynamic-form-builder and live example