我有兩個表單字段,其中如果填寫第一個字段,第二個字段是必填字段。如果我嘗試在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 –