这可能是因为Angular默认只在用户开始输入内容时启动表单验证。但是,您可以使用updateValueAndValidity()方法手动触发表单验证。例如,在模板驱动表单中,您可以在提交或重置表单之前调用此方法。
以下是一个示例,您可以在提交按钮上调用submit()方法,或者在重置按钮上调用reset()方法来使用updateValueAndValidity():
HTML:
Component:
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'my-component',
template: `...`
})
export class MyComponent {
@ViewChild('myForm', { static: false }) myForm: NgForm;
submit() {
this.myForm.form.updateValueAndValidity();
if (this.myForm.form.valid) {
// submit form
}
}
reset() {
this.myForm.resetForm();
this.myForm.form.updateValueAndValidity();
}
}
请注意,在上面的示例中,我们首先使用ViewChild装饰器获取表单(可以使用模板引用变量代替),然后在submit()和reset()方法中手动调用updateValueAndValidity()方法。如果表单通过验证,我们可以执行提交操作。