我有两个表单字段,其中如果填写第一个字段,第二个字段是必填字段。如果我尝试在Angular2中使用自定义验证器来执行此操作,验证器仅在初始化时以及特定字段发生更改时触发。Angular2相互依赖的表单字段验证
案例: - 用户填写字段1 - 字段2应成为必需,但直到用户实际更改字段2(触发自定义验证)。
private createForm():void {
this.testForm = this._formBuilder.group({
'field1': [],
'field2': ['', this.validateRequired()]
});
}
private validateRequired(){
console.log("something", this);
let component = this;
return (control: Control): { [s: string]: boolean } => {
return component.testModel.field1 && !control.value {"required":true} : null;
}
}
看到这个plunkr:http://plnkr.co/edit/PEY2QIegkqo8BW1UkQS5?p=preview
编辑:
现在我订阅了FIELD1的valueChange观察到,当改变了场2手动进行检查,如:
this.testForm.controls['field1'].valueChanges.subscribe(
value => {
component.testForm.controls['field2].updateValueAndValidity();
}
)
但我觉得必须有更好的方式来做到这一点。
参见http://stackoverflow.com/questions/31788681/angular2-validator-which-relies-on-multiple-form-fields/34582914#34582914 –