可以使用FormGroup的updateValueAndValidity()方法来手动触发表单控件的验证,也可以在控件上添加条件,只有在控件有值时才进行验证。
示例代码:
//在组件中获取FormGroup实例 formGroup: FormGroup;
ngOnInit() { this.formGroup = new FormGroup({ name: new FormControl('', Validators.required), email: new FormControl('', [Validators.required, Validators.email]) });
//页面加载完成后手动触发表单控件的验证 this.formGroup.updateValueAndValidity(); }
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function requiredIf(condition: () => boolean): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { if (condition()) { return Validators.required(control); } else { return null; } }; }
//在FormGroup中对控件进行验证 formGroup = new FormGroup({ name: new FormControl(''), age: new FormControl(''), email: new FormControl('', [ Validators.requiredIf(() => this.formGroup.get('name').value != ''), Validators.email ]) });