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

Add mock class for Form Builder group in Angular

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

  constructor(private formBuilder: FormBuilder) {

    this.userForm = this.formBuilder.group({
      'name': ['', Validators.required],
      'email': ['', [Validators.required, ValidationService.emailValidator]],
      'profile': ['', [Validators.required, Validators.minLength(10)]]
    });
  }

与其直接声明这个新值,不如使用以下信息创建 class 更好的方法:

export class UserValidator{
  something....
}

然后:

 this.userForm = this.formBuilder.group({
      UserValidator
    });

有这方面的例子吗?

您可以为此创建一个 class :

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