Angular Material select 多个显示值

Angular Material select multiple displayed value

是否可以更改 Angular Material 多个 select 中的显示值?我该怎么做,例如产品:(0/12) 取决于 selected 项目的数量。

为此使用 <mat-select-trigger>。例如:

<mat-form-field>
  <mat-select placeholder="Toppings" [formControl]="toppings" multiple>
    <mat-select-trigger>
      {{toppings.value ? toppings.value[0] : ''}}
      <span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
        (+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
      </span>
    </mat-select-trigger>
    <mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
  </mat-select>
</mat-form-field>

在此处查看演示:https://stackblitz.com/angular/qkjbojyxebly?file=app%2Fselect-custom-trigger-example.html

除了上面的答案之外,要将选择设置为初始值,这就是您在给定的 stackblitz 演示中扩展 select-custom-trigger-example.ts 的方式:

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';

/** @title Select with custom trigger text */
@Component({
  selector: 'select-custom-trigger-example',
  templateUrl: 'select-custom-trigger-example.html',
  styleUrls: ['select-custom-trigger-example.css'],
})
export class SelectCustomTriggerExample implements OnInit {
  toppings = new FormControl();

  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];

  ngOnInit()
  {
    // initalSelection could be the result from a service call (database, backend, etc.):
    let initalSelection : string [] = ["Onion","Pepperoni","Sausage"];

    // set initalSelection as inital value:
    this.toppings.setValue(initalSelection);
  }
}