我有一个表单,其中包含许多表单控件和一些控件的验证器,例如:
title = new FormControl("", Validators.compose([
Validators.required
]));
description = new FormControl("", [
Validators.required,
Validators.minLength(1),
Validators.maxLength(2000)
]);
如何添加不验证控件的另存为草稿按钮?或者删除它们?
我已经尝试了很多例子,例如:
saveDraft() {
this.addProjectForm.controls.title.clearValidators();
this.addProjectForm.controls.title.setErrors(null);
this.addProjectForm.controls.title.setValidators(null);
}
或
saveDraft() {
this.addProjectForm.controls['title'].clearValidators();
this.addProjectForm.controls['title'].setErrors(null);
this.addProjectForm.controls['title'].setValidators(null);
}
但没有任何作用..
最佳答案
试试这个:
this.addProjectForm.get('title').setValidators([]); // or clearValidators()
this.addProjectForm.get('title').updateValueAndValidity();
如果你想添加一个验证器然后追加验证器数组:
this.addProjectForm.get('title').setValidators([Validators.required]);
this.addProjectForm.get('title').updateValueAndValidity();
注意:你必须在每次更改后使用 updateValueAndValidity()
关于angular - 从表单控件 Angular 6 中删除验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53507355/