我想創建一個條件需要驗證的特定field.I嘗試通過返回Validators.required回到我的函數,但這似乎並沒有工作。我如何去做這件事?這是我的代碼:Angular2:有條件需要驗證
private _ansat: AbstractControl = new FormControl('', Validators.required);
private _helbred: AbstractControl = new FormControl('', Validators.compose([this.useValidateIfRadio(this._ansat, 0, Validators.required)]));
constructor(private _fb: FormBuilder) {
this.myForm = this._fb.group({
ansat: this._ansat,
helbred: this._helbred
});
}
useValidateIfRadio (c: AbstractControl, n: number, v) {
return function (control) {
return new Promise(resolve => {
// this.msg = ansatControl.value;
console.log(v);
if (c.value === n) {
resolve(v);
}
else {
resolve(null);
}
});
};
};
任何幫助,非常感謝。
你解決這個問題?我已經添加了一個答案,並且很好奇,如果你以相同的方式解決它(或者甚至以更好的方式) – Erex
我解決了類似的問題,如下所示的可重用自定義驗證器:[條件必需](http:// stackoverflow。 com/questions/38204812/angular2-forms-validator-with-interrelated-fields/40416197#40416197) –
啊,那看起來天才!那麼我會測試你的解決方案! – Erex