繁体   English   中英

如何在Angular2中为表单分配和验证数组

[英]How to assign and validate arrays to forms in Angular2

我在javascript中的模型( this.profile )有一个名为emails的属性,它是{email, isDefault, status}的数组

然后我将其定义如下

  this.profileForm = this.formBuilder.group({
    .... other properties here
    emails: [this.profile.emails]
  });

  console.log(this.profile.emails); //is an array
  console.log(this.profileForm.emails); // undefined

在html文件中我用它作为

    <div *ngFor="let emailInfo of profileForm.emails">
        {{emailInfo.email}}
        <button (click)="removeEmail(emailInfo)">
           Remove 
        </button>
    </div>

如果我不在formGroup添加它并将其用作数组 - 如下所示 - 它工作正常,但我有一个业务规则,该数组不应为空,我无法根据长度设置表单验证这个

  emails : [];
  this.profileForm = this.formBuilder.group({
    .... other properties here
  });

  this.emails = this.profile.emails;
  console.log(this.profile.emails); //is an array
  console.log(this.emails); // is an array

我也试过使用formBuilder.array但是那个是控件数组而不是数据数组。

   emails: this.formBuilder.array([this.profile.emails])

那么我的问题是如何将数组从模型绑定到UI以及如何验证数组的长度?

我应该如何将数组从模型绑定到UI?

好吧,我更愿意将所有来自profile.emails电子邮件推送到formArray ,否则您将获得值,但不会进行验证。

我该如何验证数组的长度?

您可以将Validators.minLength(Number)用作任何其他控件

演示代码:

零件:

export class AnyComponent implements OnInit {

  profileForm: FormGroup;
  emailsCtrl: FormArray;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit(): void {

    this.emailsCtrl = this.formBuilder.array([], Validators.minLength(ANY_NUMBER));
    this.profile.emails.forEach((email: any) => this.emailsCtrl.push(this.initEmail(email)));

    this.profileForm = this.formBuilder.group({
      // ... other controls
      emails: this.emailsCtrl
    });
  }

  private initEmail = (obj: any): FormGroup => {
    return this.formBuilder.group({
      'email': [obj.email], //, any validation],
      'isDefault': [obj.isDefault] //, any validation]
    });
  }
}

模板:

<div *ngFor="let emailInfo of emailsCtrl.value">
  {{emailInfo.email}}
  <button (click)="removeEmail(emailInfo)">
    Remove
  </button>
</div>
<div *ngIf="emailsCtrl.hasError('minlength')">
  It should have at least {{emailsCtrl.getError('minlength').requiredLength}} emails
</div>

PS1:请注意, Validators.minLength(param) 方法的 Validators.minLength(param)必须大于1,否则将无法验证。

正如您在源代码中看到的那样,当控件为空时,它会自动返回null。

然后,为了使其按预期工作,您可以添加required Validator

this.emailsCtrl = this.formBuilder.array([], Validators.compose([Validators.required, Validators.minLength(ANY_NUMBER > 1)]);

在模板中:

<div *ngIf="emailsCtrl.invalid">
  <span *ngIf="emailsCtrl.hasError('required')">
    It's required
  </span>
  <span *ngIf="emailsCtrl.hasError('minlength')">
    It should have at least {{emailsCtrl.getError('minlength').requiredLength}} emails
  </span>
</div>

PS2:

我认为在removeEmail 函数中传递要删除的电子邮件的索引更有意义,因此您不必调用indexOf来获取特定 email的索引。 你可以这样做:

<div *ngFor="let emailInfo of emailsCtrl.value; let i = index">
  {{emailInfo.email}}
  <button (click)="removeEmail(i)">
    Remove
  </button>
</div>

零件:

removeEmail(i: number): void {
  this.emailsCtrl.removeAt(i);
}

看看这个简单的DEMO

这适用于我(角度2.1.2),这种方法使您可以灵活地为电子邮件定义自定义验证:

 this.profileForm = this.formBuilder.group({
    emails: [this.profile.emails, FormValidatorUtils.nonEmpty]
    // ......
  });

export class FormValidatorUtils {

  static nonEmpty(control: any) {
    if (!control.value || control.value.length === 0) {
      return { 'noElements': true };
    }
    return null;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM