角材料MatChipList-如何在动态FormArray上使用它?

时间:2018-11-01 21:49:46

标签: javascript angular typescript angular-material angular-reactive-forms

StackBlitz

这是我的FormArray(变体):

this.productGroup = this.fb.group({
    name: '',
    variants: this.fb.array([
      this.fb.group({
        type: '',
        options: ''
      })
    ])
})

我正在使用MatChips存储字符串数组。该数组需要传递到options

<div formArrayName="variants" *ngFor="let item of productGroup.controls['variants'].controls; let i = index;">
  <div [formGroupName]="i">
    <div class="row">
      <mat-form-field class="col-12">
        <input formControlName="type">
      </mat-form-field>
    </div>
    <div class="row">
      <mat-form-field class="col-12">
        <mat-chip-list #chipList>
          <mat-chip *ngFor="let opt of typesOptions" [selectable]="true"
                    [removable]="true" (removed)="removeOpt(opt)">
            {{opt}}
            <mat-icon matChipRemove>cancel</mat-icon>
          </mat-chip>
          <input placeholder="Conjunto de opções deste Tipo"
                  formControlName="options"
                  [matChipInputFor]="chipList"
                  [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
                  [matChipInputAddOnBlur]="true"
                  (matChipInputTokenEnd)="addOpt($event)">
        </mat-chip-list>
      </mat-form-field>
    </div>
  </div>
  <div class="row">
    <a href="javascript:" (click)="addItem()"> Add Variants </a>
    <a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remove Variants </a>
  </div>
</div>

以下是方法:

// Dynamic Methods
  addItem(): void {
    this.variantsArray = this.productGroup.get('variants') as FormArray;
    this.variantsArray.push(this.fb.group({
      type: '',
      options: ''
    }));
  }
  removeItem(index: number) {
    this.variantsArray.removeAt(index);
  }

// MatChip Methods
  addOpt(item: number, event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;
    // Add our fruit
    if ((value || '').trim()) {
      this.typesOptions.push(value.trim());
    }
    // Reset the input value
    if (input) {
      input.value = '';
    }
  }
  removeOpt(opt: string): void {
    const index = this.typesOptions.indexOf(opt);
    if (index >= 0) {
      this.typesOptions.splice(index, 1);
    }

我已成功将动态字段添加到我的variants formArray中。但是MatChipList对于每个动态字段都是相同的。我还需要使MatChipList动态。有没有办法做到这一点?就像更改<mat-chip-list #chipList+i>之类。

编辑:StackBlitz

2 个答案:

答案 0 :(得分:1)

我不确定dom参考变量#chiplist是问题所在。看起来matChipList由typesOptions数组支持,但您只有一个数组。因此,每次添加matChipList组件时,它都仍由与其他所有数组相同的数组支持。您需要有一个类型数组,数组数组。然后,当您添加addItem时,还可以将一个新的子数组推入typesOptions中(并类似地为removeItem删除一个)。

我还没有编写代码,只是看代码的建议。

编辑-基于James的堆栈闪电编码了一个解决方案。

https://stackblitz.com/edit/angular-3od6rd-jkidxf

请注意,我没有详细研究delete变体如何组合在一起,理想情况下,我可能想使用一个键/值对,以dom输入元素id作为键来跟踪变体选项(在MatChipInputEvent),而不是依赖于外部循环索引。

一些来自堆栈闪电的代码:

export class ChipsOverviewExample {
  productGroup: FormGroup;
  variantsArray: FormArray;
  typesOptionsArray: string[][] = [];
  readonly separatorKeysCodes: number[] = [ENTER, COMMA];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.productGroup = this.fb.group({
      name: '',
      variants: this.fb.array([
        this.fb.group({
          type: '',
          options: ''
        })
      ]),
    });
    this.typesOptionsArray.push([]);
  }

  saveProduct(form: FormGroup) {
    console.log(form);
  }

  // Add new item to FormArray
  addItem(): void {
    this.variantsArray = this.productGroup.get('variants') as FormArray;
    this.variantsArray.push(this.fb.group({
      type: '',
      options: ''
    }));

    this.typesOptionsArray.push([]);
  }

  removeItem(index: number) {
    this.variantsArray.removeAt(index);
  }

  addOpt(event: MatChipInputEvent, index: number): void {
    const input = event.input;
    const value = event.value;
    // Add our fruit
    if ((value || '').trim()) {
      this.typesOptionsArray[index].push(value.trim());

    }
    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  removeOpt(opt: string, index: number): void {
    const optIndex = this.typesOptionsArray[index].indexOf(opt);
    if (optIndex >= 0) {
      this.typesOptionsArray[index].splice(optIndex, 1);
    }
  }
}

答案 1 :(得分:0)

尝试使formGroup成为新组件,并向其输入formGroup(而不是formGroupName)。

<div formArrayName="variants" *ngFor="let item of productGroup.controls['variants'].controls; let i = index;">
  <variant [varientGroup]="item"><varient>
  <div class="row">
    <a href="javascript:" (click)="addItem()"> Add Variants </a>
    <a href="javascript:" (click)="removeItem(i)" *ngIf="i > 0"> Remove Variants </a>
  </div>
</div>

variant component.html

<div [formGroup]="varientGroup">
 <div class="row">
    <mat-form-field class="col-12">
      <input formControlName="type">
    </mat-form-field>
 </div>
 <div class="row">
    <mat-form-field class="col-12">
      <mat-chip-list #chipList>
        <mat-chip *ngFor="let opt of typesOptions" [selectable]="true"
                [removable]="true" (removed)="removeOpt(opt)">
          {{opt}}
          <mat-icon matChipRemove>cancel</mat-icon>
        </mat-chip>
        <input placeholder="Conjunto de opções deste Tipo"
              [matChipInputFor]="chipList"
              [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
              [matChipInputAddOnBlur]="true"
              (matChipInputTokenEnd)="addOpt($event)">
      </mat-chip-list>
    </mat-form-field>
  </div>
</div>

在varient.component.ts

@Input()varientGroup: FormGroup