2
後FormGroup我有這個FormGroup如何setValidators初始化
defaultIdNumberValidator = [Validators.required, Validators.minLength(6),
Validators.maxLength(11)];
this.registerForm = this.formBuilder.group({
permissions: this.formBuilder.group({
country: ['', [Validators.required]],
identityNumber: [null, this.defaultIdNumberValidator],
}, {validator: [this.validateId]})
});
,我想清楚了,並取決於this.validateId
方法一定條件下增加驗證到identityNumber
。
validateId(input: AbstractControl) {
if(condition) {
input.get("identityNumber").clearValidators(); //this is working
}
if(condition) {
input.get("identityNumber").setValidators(this.defaultIdNumberValidator); //not working
}
}
當setValidators
方法被調用我得到這個錯誤(行:109行,其中setValidators
叫)
ERROR TypeError: Cannot read property 'defaultIdNumberValidator' of undefined
at RegisterComponent.validateId (register.component.ts:109)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
UPDATE:
我重新啓動開發服務器,現在我得到這個錯誤
ERROR TypeError: Cannot read property 'setValidators' of undefined
at RegisterComponent.validateId (register.component.ts:109)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
at eval (forms.js:742)
at Array.map (<anonymous>)
at _executeValidators (forms.js:742)
at eval (forms.js:694)
更新2:
我創建簡單的plunker重現錯誤。如果你第一次點擊輸入,而不是點擊其他地方,你會得到錯誤。因此,當輸入值的長度> = 2時應該刪除該錯誤,並且當>> 5時應該再次可見。我也不知道爲什麼錯誤在輸入值的長度爲3且不是2時消失...
你能創建一個plunkr?你的validateId方法是否在一個單獨的ts文件中? –
你顯然在失去對'this'的引用 –
查看更新。我會嘗試創建一個plunkr –