首页 > 解决方案 > 使用表单构建器和角材料芯片添加一组对象

问题描述

我正在尝试使用角材料芯片创建一组标签对象。

我发现很难弄清楚如何将这些标签对象推送到我的表单构建器中的数组中。

它应该很简单,因为我有一个名为“selected”的数组来保存标签对象,我只想将它添加到我的表单构建器中。

这是我的 HTML:

<form class="flex col" (ngSubmit)="onSubmit()" [formGroup]="registerForm">
    <mat-form-field class="chip-container">
            <mat-chip-list #chipList>
              <mat-chip *ngFor="let tag of selected" [removable]="removable" (removed)="onRemove(tag)">
                {{tag.Text}}
                <i matChipRemove *ngIf="removable" class="fal fa-times-circle"></i>
              </mat-chip>
              <input placeholder="{{placeholder}}" [matChipInputFor]="chipList"
                [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur"
                (matChipInputTokenEnd)="add($event)" disabled>
            </mat-chip-list>
          </mat-form-field>

<div class="available-chips-container">
        <mat-chip-list *ngIf="!hideAvailable">
          <mat-chip *ngFor="let tag of tags" [selectable]="selectable" (click)="onSelect(tag)">
            {{tag.Text}}
          </mat-chip>
        </mat-chip-list>
        <p class="danger-text" *ngIf="hideAvailable">Great! You have selected the maximum number of tags.</p>
      </div>
</form>

这是我的组件代码:

  hideAvailable: boolean;
  selectable = true;
  removable = true;
  placeholder = 'Select a tag below...';
  selected: ITag[] = [];
  tags: ITag[];

  this.registerForm = this.fb.group({
      Email: new FormControl('', [Validators.required, Validators.email]),
      Password: new FormControl('', Validators.required),
      ConfirmPassword: new FormControl('', Validators.required),
      Firstname: new FormControl('', Validators.required),
      Lastname: new FormControl('', Validators.required),
      DateOfBirth: new FormControl('', Validators.required),
      Tags: this.selected
  });

onSelect(tag: ITag) {
  this.selected.push(tag);
}

onRemove(tag: ITag): void {
  this.tags.push(tag);
}

onSubmit() {
  console.log(this.registerForm.value)
}

目前的问题是,虽然我将标签推送到选定的数组中并且它们被很好地推送,但是当使用 onSubmit() 提交表单时,registerForm.value 标签数组始终为空。

如果您需要任何进一步的代码,请告诉我。

谢谢

标签: angularangular-materialangular2-formbuilder

解决方案


selected似乎只是一个 JS 数组,而不是FormArray. 您需要告诉 angular selected 是 aFormArray并且根据具体情况,将表单控件或表单组推送到该数组中。我猜你在这种情况下想要表单组。因此,在构建表单时声明一个表单数组:

constructor(private fb: FormBuilder) {
  this.registerForm = this.fb.group({
    Email: ['', [Validators.required, Validators.email]],
    // ...
    Tags: this.fb.array([])
  });
}

然后在添加时,我们将表单组推送到表单数组,我们为表单数组定义了一个 getter,以便在函数和模板中使用。

get tagsArr() {
  return this.registerForm.get('Tags') as FormArray;
}

然后添加和删除:

onSelect(tag: any) {
  /** if you only want formcontrol with a single value use: 
      this.tagsArr.push(tag.Text), else do below
  **/
  this.tagsArr.push(
    this.fb.group({
      Text: tag.Text
      // other props
    })
  )
}

onRemove(index): void {
  this.tagsArr.removeAt(index);
}

然后在模板中我们迭代formarray并显示表单控件值:

<mat-chip-list #chipList formArrayName="Tags">
  <mat-chip *ngFor="let tag of tagsArr.controls; let i = index" 
                    [removable]="true" (removed)="onRemove(i)" >
    {{tag.get('Text').value}}
    <i matChipRemove *ngIf="removable" class="fal fa-times-circle"></i>
  </mat-chip>
</mat-chip-list>

StackBlitz示例


推荐阅读