6

我正在使用 Angular 6 和 Angular 材质。我正在尝试从 mat-chip 和自动完成中保存选定对象或选定对象列表。我能够将字符串值发送到 fruits[] 数组,但不能将选定的对象发送到 fruits[] 数组。请帮我找到解决方案。谢谢。

我的演示项目链接:stackblitz 上的演示代码

4

2 回答 2

14

你可以试试这个解决方案。

我在Stackblitz创建了一个演示。

组件.html

<mat-form-field class="example-chip-list">
    <mat-chip-list #chipList>
        <mat-chip *ngFor="let fruit of fruits;let indx=index;" [selectable]="selectable" [removable]="removable" (removed)="remove(fruit,indx)">
            {{fruit.name}}
            <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
        </mat-chip>
        <input placeholder="New fruit..." #fruitInput [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"
         [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)">
    </mat-chip-list>
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
        <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
            {{fruit.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>


<pre>{{fruits|json}}</pre>

组件.ts

import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocompleteSelectedEvent, MatChipInputEvent } from '@angular/material';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

/**
 * @title Basic chips
 */
@Component({
  selector: 'chips-overview-example',
  templateUrl: 'chips-overview-example.html',
  styleUrls: ['chips-overview-example.css'],
})
export class ChipsOverviewExample {
  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = false;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  fruitCtrl = new FormControl();
  filteredFruits: Observable<string[]>;
  fruits: any = [];
  allFruits: any = [
    {
      id: 1,
      name: 'Apple'
    },
    {
      id: 2,
      name: 'Orange'
    },
    {
      id: 3,
      name: 'Banana'
    },
    {
      id: 4,
      name: 'Malta'
    }
  ];

  @ViewChild('fruitInput') fruitInput: ElementRef;

  constructor() {
    this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
      startWith(null),
      map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
  }

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;
    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push({
          id:Math.random(),
          name:value.trim()
      });
    }

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

    this.fruitCtrl.setValue(null);
  }

  remove(fruit, indx): void {
    this.fruits.splice(indx, 1);
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.value);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

  private _filter(value: any): string[] {
    return this.allFruits.filter(fruit => fruit.id === value.id);
  }
}
于 2018-07-09T06:50:29.080 回答
5

我一直在开发一个使用自动完成从列表中选择对象的应用程序。使用与 Krishna Rathore 类似的方法,我发现 FormControl valueChanges 事件不能可靠地返回一个字符串(有时我得到一个对象)。我的解决方案是添加一个 Observable<String[]> 并将其用于 mat-autocomplete。我还添加了一个名为 allowFreeTextAddEngineer 的属性来处理您的应用程序可能允许自动完成列表中的条目以外的条目的情况。这里有一个演示

于 2018-11-01T22:20:47.557 回答