2017-12-18 405 views
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時消失...

+0

你能創建一個plunkr?你的validateId方法是否在一個單獨的ts文件中? –

+0

你顯然在失去對'this'的引用 –

+0

查看更新。我會嘗試創建一個plunkr –

回答

2

您需要bind(this)才能保留this的上下文。您還需要使用updateValueAndValidity來更改要更新的驗證器。在那裏,我們也不需要發出一個事件,如果你是這樣的話,這種情況會循環,直到你的瀏覽器崩潰。所以改變如下:

}, {validator: this.validateId.bind(this)}) 

和驗證是這樣的:

validateId(input: AbstractControl) { 
    // ... 
    if(...) { 
    input.get("identityNumber").clearValidators(); 
    input.get("identityNumber").updateValueAndValidity({emitEvent:false, onlySelf:true}); 
    } 
    if(...) { 
    input.get("identityNumber").setValidators(this.defaultIdNumberValidator); 
    input.get("identityNumber").updateValueAndValidity({emitEvent:false, onlySelf:true}); 
    } 
} 

PLUNKER