[Fixed] Check for invalid inputs on ngIF Angular 11


The code


buildForm() {
    this.commentForm = this.fb.group({
      name: [
      comment: ['', [Validators.required]],


<div fxFlex *ngIf="commentForm.value.name && commentForm.value.comment">
      <mat-list fxFlex>
        <div matLine><span>{{ commentForm.value.comment }}</span></div>
        <div matLine><span><b>{{ commentForm.value.name }}</b></span></div>

The Context: I got a required validator working writen in the .ts file for both the "name" and "comment" however the name has another validator attached to it which is check if the name has 3 or more characters

The issue: I got the code (above) mostly working that the div is hidden when the name and comment is empty however once the user types in the name of 2 characters or less, the div shows up — I know I am missing a conditional here but Angular is fairly new to me so I dont know how to check for invalid inputs on an ngIf statement or is there something else that needs to be done for it (write a function then attached it on the template)?

What I have tried: I have tried putting "commentForm.value.invalid", "commentForm.value.name.invalid" & "commentForm.invalid" as part of the conditionals but no good.

Kindly help


You could show the relevant error messages as below.

<div fxFlex *ngIf="commentForm.controls['name'].invalid && (commentForm.controls['name'].dirty || commentForm.controls['name'].touched)">
  <mat-list fxFlex>
    <div matLine *ngIf="commentForm.controls['name'].errors.required">
        Required error message here
    <div matLine *ngIf="commentForm.controls['name'].errors.minLength">
        Min length error message here
    <div matLine *ngIf="commentForm.controls['name'].errors.maxLength">
        Max length error message here

Leave a Reply

(*) Required, Your email will not be published