0

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!

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.