在Angular中,可以使用markAsTouched()
方法来改变表单控件的验证状态,即使没有对应的值改变。
下面是一个示例代码:
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`,
})
export class FormComponent {
nameControl = new FormControl('', Validators.required);
submitForm() {
// 标记表单控件为已触摸过
this.nameControl.markAsTouched();
if (this.nameControl.valid) {
// 如果表单控件验证通过,提交表单
console.log('Form submitted');
}
}
}
在上述示例中,nameControl
是一个FormControl
对象,使用Validators.required
验证器来确保输入框中的值不为空。
在submitForm()
方法中,我们调用了markAsTouched()
方法来标记nameControl
控件为已触摸过。即使没有对应的值改变,这个方法也会改变控件的验证状态。
如果nameControl
控件通过验证,我们可以继续执行其他操作,比如提交表单。