6

this.profile我在 javascript 中的模型 ( ) 有一个名为 的属性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 以及我应该如何验证数组的长度?

4

2 回答 2

8

我应该如何将数组从模型绑定到 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) 方法的参数必须大于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

于 2017-02-20T20:50:53.043 回答
5

这对我有用(角度 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;
  }
}
于 2017-02-20T20:50:19.787 回答