我有一个类似下面的表格
this.personForm = new FormGroup({
title: new FormControl(this.person.salutation, Validators.compose([
Validators.minLength(2)
])),
firstName: new FormControl(this.person.firstName, Validators.compose([
Validators.minLength(4)
])),
});
基于来自API调用的配置,我希望使它们成为动态需要或不需要的。我知道我可以使用formControl.setValidators([Validators.required])
,但这将清除现有的验证器。
我希望通过以下方式之一实现它
addValidators([])
)的功能getValidators()
)不幸的是(据我所知)以上两个功能都不存在。那么,如何在不知道已有控件的情况下向formControl添加新的Validation?
答案 0 :(得分:1)
我想您可以使用取决于一个变量的customValidator,在示例中,按钮使变量“还”为true或false。取决于表单是否有效
@Component({
selector: 'my-app',
template:`
<form [formGroup]="personForm">
<input formControlName="title"/>
<input formControlName="firstName"/>
</form>
<button (click)="addValidator()">click</button>
<hr/>
{{personForm?.errors|json}}
{{personForm?.valid}}`
})
export class AppComponent implements OnInit {
yet: boolean;
personForm: FormGroup;
person = { salutation: "", firstName: "" }
ngOnInit() {
this.personForm = new FormGroup({
title: new FormControl(this.person.salutation, Validators.compose([
Validators.maxLength(2)
])),
firstName: new FormControl(this.person.firstName, Validators.compose([
Validators.minLength(4)
])),
}, this.customValidator())
}
addValidator() {
this.yet = !this.yet;
this.personForm.updateValueAndValidity();
}
customValidator() {
return (group: FormGroup) => {
if (!this.yet)
return null;
if (group.get('title').value == '')
return { title: 'required' }
}
}
请参阅stackblitz