Search code examples
angularangular-materialangular7angular-formbuilderangular-material-7

ERROR TypeError: "_co.bankId is undefined" (Angular 7)


I have a subproject in my angular app. In this subproject I want to create a form with input fields. These fields need a validation and need to show an error optionally, if the field is invalid (e.g. required). Well, the problem is, the "formControlName" property is undefined (look at the title of this thread).

The code is defined as follows:

// Component file:
...
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
...

export class ConfigFormComponent implements OnInit {
  orderReport: FormGroup;

  createForm() {
    return this.fb.group({
      bankId: ['', Validators.required],
      ...
    });
  }

  constructor(private fb: FormBuilder) { 
    this.orderReport = this.createForm();
  }
}

and the HTML:

 // View file:
    ...
    <mat-card>
       <form [formGroup]="orderReport">
          <mat-form-field appearance="fill">
             <mat-label>Bank ID</mat-label>
             <input matInput placeholder="Bank ID" formControlName="bankId" required>
             <mat-error *ngIf="bankId.invalid">The field shows an error.</mat-error>
          </mat-form-field>
          ...
       </form>
    </mat-card>

I also added the FormsModule and ReactiveFormsModule to the AppModule file. Have anyone an idea?

I'm using Angular 7.3.2 with Angular Material 7.3.2.


Solution

  • To access the validation status of a form control, you need to get a reference to that form control, in your case using: orderReport.get('bankId'), then you can access invalid.

    Your HTML code should be:

    <mat-error *ngIf="orderReport.get('bankId').invalid">The field shows an error.</mat-error>