在具有全局验证的字段上显示错误



我想在表单上实现全局验证,并根据此验证更改一些输入的颜色。

我有三块田地。只有当第一个字段的值为"test"时,才需要两个字段。

以下是我实现的:

function typeValidator(form: FormGroup) {
const type = form.controls['field1'].value;
if (type === 'test') {
const field2 = form.controls['field2'].value;
const field3 = form.controls['field3'].value;
return (!field2 || !field3) ? { requiredIf: true } : null;
}
return null;
}

关于HTML:

<mat-form-field color="accent">
<mat-select formControlName="field1" placeholder="Field1">
<mat-option value="test">Test</mat-option>
<mat-option value="other">Other</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field color="accent">
<mat-select formControlName="field2" placeholder="Field2">
<mat-option *ngFor="let element of elements" [value]="element.id">{{element.name}}</mat-option>
</mat-select>
</mat-form-field>

验证工作正常,但我想在表单出现requiredIf类型的验证错误时,将field2的颜色更改为橙色。

谢谢你的帮助。Thierry

typeValidator作为自定义验证器添加到所需字段中。您可以通过myFormControl.hasError('myError')检查表单控件是否存在自定义错误。该条件可以在类语句中用于根据错误状态添加/删除类。

最新更新