angular - 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
}
谢谢
解决方案
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
}
推荐阅读
- c - '(struct student *)&st' 是一个指针;你的意思是使用'->'吗?|
- python - 在 3 个不同的集合中获得所有可能的组合
- c# - 如何知道一个 GameObject 在 Unity 中是否有网格?
- c++ - Toolbar / CreateToolbarEx 问题 C++ 不显示所有位图
- google-colaboratory - 图片无法在google colab中显示
- android - 在 xamarin 形式的初始屏幕中动画或从底部到顶部的过渡?
- r - 在 R Shiny 中,如何在服务器中获取 selectInput 的选择?
- python - 如何评估UMAP中保留的信息?
- python - 在 discord.py 中删除图像后,如何让机器人复制图像的 url 链接
- c - 尝试使用 C 和矩阵显示 X,但有些不对劲