可以使用Angular的内置验证器以及自定义验证器。当表单控件处于无效状态时,可以触发动态验证。下面是一个示例代码:
该输入项为必填项。
该输入项不符合规范。
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit {
myFormControl: FormControl;
ngOnInit() {
this.myFormControl = new FormControl('', [
Validators.required,
this.customValidator // 自定义验证器
]);
}
customValidator(control: FormControl): {[key: string]: any} | null {
const value = control.value;
// 判断输入值是否符合规范
if (value) {
return null;
}
return { 'customValidator': { value } };
}
}
上述代码中,myFormControl
是一个表单控件,它具有内置的required
验证器以及自定义的customValidator
验证器。在HTML代码中,使用ngClass
指令来动态绑定CSS类,当myFormControl
处于无效状态并且用户已经访问过该控件时,添加is-invalid
类。同时,使用*ngIf
指令来控制显示无效反馈信息。如果输入项为空,则显示“该输入项为必填项”,否则显示“该输入项不符合规范”。