Search code examples
angularangular-materialangular-formsangular8mat-input

checking form control input for errors by using it as a variable


I'm using angular 8 with angular material to write my website.

I have a form with formGroup created and I want to be able to use *ngIf to check for validation errors by using the actual input element as a parameter.

currently this is my working code:

I have the following form:

<form [formGroup]="queryForm" (submit)="runQuery()">
...
  <mat-form-field>
            <input matInput #timezone placeholder="Timezone" aria-label="Timezone" formControlName="timePeriodTimeZone"/>
            <mat-hint>timezone as a number</mat-hint>
            <mat-error *ngIf="hasError('timePeriodTimeZone','required')">timezone required</mat-error>
        </mat-form-field>
...
</form>

and in the class of the component I implemented the hasError() function like this:

 public hasError = (controlName: string, errorName: string) =>{
    return this.queryForm.controls[controlName].hasError(errorName);
  }

and of course I configured the queryForm variable as a group created by form builder.

is there a way to check the error without calling a function from the class itself?

since I added #timezone to the input field I assumed i will be able to do something like:

<mat-error *ngIf="timezone.hasError('required')">timezone required!</mat-error>

but I can't! :)

I would prefer to use something like that cause I want to create an error handling component with some mat-errors so I will be able to reuse it in each input field and I would like to paste to it the input control instead of the entire form group.

any information regarding this issue would be greatly appreciated.

thanks!


Solution

  • you know that if the field has a unique validator, you can use simply

    <mat-error>timezone required!</mat-error>
    

    (the *ngIf is not necesary).

    if you want has a big control of errors, you can has some like

    <mat-error >{{getError('timezone')}}</mat-error>
    

    and you has a function like

    getError(field:string)
    {
       const control=this.myForm.get(field);
       string error=''
       switch (field)
        case 'timezone':
           error=control.hasError('required')?'time zone required':
                  control.hasError('other')?' other error':''
        break;
        case '....'
       }
       return error;
    }