Mat-error not working properly with mat-select

  angular, angular-material

I’m making a form and I want to add an error throw if there is no value.

For the text inputs it’s okay, but with the <mat-select> it’s not working.

Here is the declaration of the mat-select in the .ts file :

    {
        id: 'role',
        label: marker('USER.role'),
        type: 'select',
        values: [],
        control: new FormControl('', [Validators.required]),
        required: true
    }

And the HTML :

<mat-form-field class="block" *ngIf="field.type == 'select'">
    <mat-label>{{ field.label | translate }}</mat-label>
    <mat-select [(value)]="field.control.value" [required]="field.required">
        <mat-option *ngFor="let option of field.values" [value]="option['id']">{{ option['label'] }}</mat-option>
    </mat-select>
    <mat-error *ngIf="field.control.invalid">{{ getErrorMessage(field.id) }}</mat-error>
</mat-form-field>

The getErrorMessage is like this :

getErrorMessage(field: any) {
    let error = undefined;
    this.userForm.forEach(element => {
        if(element.id == field)
            if (element.required){
                error = this.translate.instant('AUTH.field_required');
            }
    })
    return error
}

Thanks

Source: Angular Material Quesions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.