Angular 2 - 控制初始化后添加验证器 [英] Angular 2 - Add validator after control initialization
问题描述
我想知道如何将验证器添加到已创建的formControl中(它是使用它自己的验证器创建的)。但是,让我们想象一下,在延迟一段时间之后,我想添加另一个(或者我有一个包含几个验证器的自定义控件本身),并且我想创建外部Reactive窗体并将内部验证器添加到外部。
I am wondering how I can add an validator to already created formControl (that was created with it own Validators). But, let's imagine that after some delay I want to add another one (or I have a custom control that contains a few validators itself) and I want to create outer Reactive form and add inner validators to outer.
可能吗?我没有找到任何信息(仅限于重新设置所有验证器)
感谢您的帮助!
Is it possible? I didn't found any information (only about re-setting all validators) Thanks for any help!
this.testForm = this.fb.group({
testField: [{value: '', disabled: false}, [<any>Validators.required]]
})
<form [formGroup]="testForm" novalidate>
<custom_input>
formControlName="testField"
[outerFormControl]="testForm.controls.testField"
</custom_input>
</form>
之后,我想在自定义控件中添加其他验证器。我怎么能做到这一点?
and after that I want to add other validator inside my custom controls. How I can do that?
custom_coontrol.ts
custom_coontrol.ts
this.outerFormControl.push(Validators.maxLength(10));
推荐答案
@Component({
selector: 'my-app',
template: `
<form [formGroup]="testForm" novalidate>
<input type="text" formControlName="age">
</form>
<button (click)="addValidation()">Add validation</button>
{{ testForm.valid | json }}
`,
})
export class App {
constructor(private fb: FormBuilder) {
this.testForm = this.fb.group({
age: [null, Validators.required]
})
}
addValidation() {
this.testForm.get('age').setValidators(Validators.maxLength(2));
}
}
这篇关于Angular 2 - 控制初始化后添加验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!