在Angular中为Form Builder组添加模拟类

时间:2019-02-13 10:49:11

标签: angular typescript formbuilder

我正在创建许多新表单,例如:

  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
    });

有什么例子吗?

1 个答案:

答案 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());