• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如何setValidators初始化

angular 来源:Domen Jakofčič 3次浏览

后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时消失…


===========解决方案如下:

您需要bind(this)才能保留this的上下文。您还需要使用updateValueAndValidity来更改要更新的验证器。在那里,我们也不需要发出一个事件,如果你是这样的话,这种情况会循环,直到你的浏览器崩溃。所以改变如下:

<code class="prettyprint-override">}, {validator: this.validateId.bind(this)}) 
</code>

和验证是这样的:

<code class="prettyprint-override">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}); 
    } 
} 
</code>

PLUNKER


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)