Dha*_*ari 3 angular angular-reactive-forms angular-formbuilder
I was trying to use extra parameter map provided by Angular FormBuilder
group(controlsConfig: {
[key: string]: any;
}, extra: {
[key: string]: any;
} | null = null): FormGroup
Run Code Online (Sandbox Code Playgroud)
Docs : FormBuilder
But facing
this.validator is not a function
If i pass a single validator instead of an array, the above error vanishes but the validation does not happen?
Can someone help me with this or provide the correct way of using the extra map parameter?
My component and its corresponding template is as follows:
app.component.ts
import { Component } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
formGroupNew: FormGroup;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.formGroupNew = this.fb.group(
{ name: "Provide name"},
{ validator: [Validators.required, Validators.maxLength(5)] } );
}
validate() {
console.log(this.formGroupNew.controls["name"].status);
}
}
Run Code Online (Sandbox Code Playgroud)
app.component.html:
<div class="container" [formGroup]="formGroupNew">
<input class="form-control" formControlName="name">
<button (click)="validate()">Validate</button>
</div>
Run Code Online (Sandbox Code Playgroud)
当您这样做时fb.group({...}, {validator: fn}),第一个参数是组的控件,第二个参数是组对象本身的配置参数,而不是其中包含的控件。
导致错误的原因是该方法希望根据src接收函数而不是数组。
在ValidatorFn您能通过会有应用于FormGroup对象,所以你可以创建自定义函数来检查该组中多个控件的条件。出于这个原因,传递类似的东西是没有意义的Validators.length(5),因为组的值是一个对象(您将如何根据对象检查该条件?)。相反,这Validators.required是有道理的,因为当未设置所有控件时,该值可能为 null。
假设您有两个自定义验证器函数:CustomValidatorFnOne,CustomValidatorFnTwo并且您想将它们应用到组加上所需的。你可以这样做:
fb.group({...}, {
validator: Validators.compose(
[
CustomValidatorFnOne,
CustomValidatorFnTwo,
Validators.required
]
)
})
Run Code Online (Sandbox Code Playgroud)
这样你就可以将所有验证器组合成一个函数。
| 归档时间: |
|
| 查看次数: |
10825 次 |
| 最近记录: |