我正在创建许多新表单,例如:
constructor(private formBuilder: FormBuilder) {
this.userForm = this.formBuilder.group({
'name': ['', Validators.required],
'email': ['', [Validators.required, ValidationService.emailValidator]],
'profile': ['', [Validators.required, Validators.minLength(10)]]
});
}
与其直接声明此新值,不应该是使用此类信息创建类的更好方法:
export class UserValidator{
something....
}
然后:
this.userForm = this.formBuilder.group({
UserValidator
});
有什么例子吗?
答案 0 :(得分:1)
您可以为此创建一个类:
export class User {
name: string;
email: string;
profile: string;
toFormGroup() {
return {
name: [this.name, Validators.required],
email: [this.email, [Validators.required, ValidationService.emailValidator]],
profile: [this.profile, [Validators.required, Validators.minLength(10)]]
};
}
}
现在您可以像这样使用它:
const user = new User();
user.name = 'John Doe';
this.form = this.fb.group(user.toFormGroup());