问题描述: 在Angular中,调用updateValueAndValidity()方法后,表单验证仍然不起作用。
解决方法:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
`,
})
export class MyFormComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
myControl: new FormControl('', Validators.required)
});
}
updateValidation() {
this.myForm.controls['myControl'].updateValueAndValidity();
}
}
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
`,
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
myControl: new FormControl('', Validators.required)
});
}
updateValidation() {
this.myForm.controls['myControl'].updateValueAndValidity();
}
}
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-my-form',
template: `
`,
})
export class MyFormComponent implements OnInit {
myForm: FormGroup;
showControl: boolean = false;
ngOnInit() {
this.myForm = new FormGroup({
myControl: new FormControl('', Validators.required)
});
}
updateValidation() {
if (this.showControl) {
this.myForm.controls['myControl'].updateValueAndValidity();
}
}
}
以上是几种可能的解决方法,根据具体情况选择适合的方法。如果问题仍然存在,请检查其他可能的错误,比如表单控件的命名是否正确,或者是否存在其他自定义验证器等。