首页 > 解决方案 > Mat-error 无法与 mat-select 一起正常工作

问题描述

我正在制作一个表格,如果没有价值,我想添加一个错误抛出。

对于文本输入,它没关系,但<mat-select>它不起作用。

这是 .ts 文件中 mat-select 的声明:

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

和 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>

getErrorMessage是这样的:

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
}

谢谢

标签: angularangular-material

解决方案


FormControl您可以通过 usinggetError方法访问错误。

https://angular.io/api/forms/AbstractControl#getError

getErrorMessage(field: any) {
    let error = undefined;
    const formControl = this.field.control as FormControl;
        if (formControl.getError('required')){
            error = this.translate.instant('AUTH.field_required');
        }
    })
    return error
}

推荐阅读