首页 > 解决方案 > 是否可以同时使用 mat-select 和 mat-chips?

问题描述

我想知道是否有可能“混合” mat-selectand mat-chip-list。在 中chip-list,我想显示从中选择的选项mat-select

如果是,我该怎么做?

标签: angularangular-material

解决方案


是的,有可能。您需要<mat-select-trigger><mat-select>. 里面<mat-select-trigger>的地方<mat-chip-list>

在您的 HTML 模板中,您需要以下内容:

<mat-form-field>
  <mat-label>Toppings</mat-label>
  <mat-select [formControl]="toppingsControl" multiple>

    <mat-select-trigger>
      <mat-chip-list>
        <mat-chip *ngFor="let topping of toppingsControl.value"
          [removable]="true" (removed)="onToppingRemoved(topping)">
          {{ topping }}
          <mat-icon matChipRemove>cancel</mat-icon>
        </mat-chip>
      </mat-chip-list>
    </mat-select-trigger>

    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>

  </mat-select>
</mat-form-field>

<br/> <!-- only for debug -->
{{ toppingsControl.value | json }}

在你的ts

@Component({
  selector: 'select-multiple-example',
  templateUrl: 'select-multiple-example.html',
  styleUrls: ['select-multiple-example.css'],
})
export class SelectMultipleExample {
  toppingsControl = new FormControl([]);
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

  onToppingRemoved(topping: string) {
    const toppings = this.toppingsControl.value as string[];
    this.removeFirst(toppings, topping);
    this.toppingsControl.setValue(toppings); // To trigger change detection
  }

  private removeFirst<T>(array: T[], toRemove: T): void {
    const index = array.indexOf(toRemove);
    if (index !== -1) {
      array.splice(index, 1);
    }
  }

}

这是 Angular Material 9 的完整示例,但它在版本 6 中的工作方式相同。

我希望这有帮助!

演示


推荐阅读