Search code examples
angularangular-materialangular-reactive-formsangular-material2angular-validation

Angular does not throw an error when accessing an unknown property on a form control's error object


Define an angular reactive form with a bunch of different form controls and validators defined for a few controls. Define a getter property in .ts file as shown below.

  get formControls(): {[key: string]: AbstractControl} {
    return this.testForm.controls;
  }

In the the html, define a <mat-error> with an *ngIf as shown below

      <mat-form-field appearance="fill">
        <mat-label>First Name</mat-label>
        <input matInput placeholder="Item Name" formControlName="firstName">
        <mat-error *ngIf="formControls.firstName.errors?.maxLength">First Name cannot exceed 25 characters</mat-error>
      </mat-form-field>

maxLength property is incorrect and does not exist on errors object on a form control. The correct property is maxlength. Why does angular not throw an error when an incorrect property is used?

It took so long to determine that the property name was wrong and that is the reason the message defined inside of mat-error was not being displayed in html.

Is that a bug with Angular or is there something that I'm missing or implementing incorrectly?

Thanks to everyone taking time to answer this question.


Solution

  • This is how JavaScript works. If an object does not have a key, it will return undefined when trying to access it and not throw an exception as in other languages. undefined is falsy, so !!undefined evaluates to false.

    const obj = {a: 10};
    console.log(obj.b) // undefined
    

    In your example formControls.firstName.errors?.maxLength is undefined as errors does not have a property with named maxLength.