Skip to content

Misleading *ngIf attribute in <mat-error> example? #18430

@fterrani

Description

@fterrani

Documentation Feedback

I was working on form validation and wanted to take advantage of <mat-error> elements. I based my code on the following example:

<div class="example-container">
  <mat-form-field appearance="fill">
    <mat-label>Enter your email</mat-label>
    <input matInput placeholder="pat@example.com" [formControl]="email" required>
    <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
  </mat-form-field>
</div>

As many, I thought at first that it was possible to use <mat-error> for its aesthetics only and that using a FormControl was optional. But apparently, <mat-error> shows up only if there is a FormControl used at some point, and if that FormControl is in an error state. The docs also state that:

If a form field can have more than one error state, it is up to the consumer to toggle which messages should be displayed. This can be done with CSS, ngIf or ngSwitch.

Which means, if I got that right, that *ngIf is more of an additional condition deciding if <mat-error> is displayed and has no effect if the FormControl isn't already in an error state. According to my tests, this seems to be the case. If I am right, I think this line is incredibly misleading:

<mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>

Because that *ngIf="email.invalid" does not dictate if the <mat-error> element is displayed (something anyone sane thinks it does at first sight), nor does it have any interesting effect in this example since email.invalid seems to always be true if the <mat-error> element is displayed. During my tests, having *ngIf="email.invalid" or not did not make any difference.

Consequently, I suggest:

  • that *ngIf="email.invalid" is removed from the aforementioned example,
  • that <mat-error>'s dependency on using a FormControl is explicitly mentioned in the docs
  • and that, maybe, another example showing how the *ngIf is used to handle several error messages in the template (instead of using getErrorMessage() in the component's TS file) is added.

Affected documentation page: https://material.angular.io/components/form-field/overview#error-messages

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4A relatively minor issue that is not relevant to core functionsarea: material/form-fielddocsThis issue is related to documentationneeds: discussionFurther discussion with the team is needed before proceeding

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions