如何setValidators初始化

后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来更改要更新的验证器。在那里,我们也不需要发出一个事件,如果你是这样的话,这种情况会循环,直到你的浏览器崩溃。所以改变如下:

}, {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

以上是 如何setValidators初始化 的全部内容, 来源链接: utcz.com/qa/262952.html

回到顶部