Is it possible to use mat-select and mat-chips together?

穿精又带淫゛_ 提交于 2020-05-13 07:31:09

问题


I wanna know if it's possible have a "mix" of mat-select and mat-chip-list. In the chip-list, I want to show the selected options from mat-select.

If it is, how can I do it?


回答1:


Yes, it is possible. You need to use <mat-select-trigger> within <mat-select>. Inside <mat-select-trigger> place <mat-chip-list>.

In your HTML template you need something like:

<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 }}

And in your 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);
    }
  }

}

Here is a complete example with Angular Material 9, but it works the same in version 6.

I hope this helps!




回答2:


You can do this by pushing the selected values to a variable and read this variable in the mat-chip-list.

HTML:

<mat-form-field>
  <mat-label>Select an option</mat-label>
  <mat-select [(value)]="selected" multiple>
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>
<mat-chip-list>
  <mat-chip *ngFor="let value of selected">{{value}}</mat-chip>
</mat-chip-list>

TS:

import {Component} from '@angular/core';

@Component({
  selector: 'my-example',
  templateUrl: 'my-example.html',
  styleUrls: ['my-example.css'],
})
export class MyExample {
  selected: string[] = [];
}


来源:https://stackoverflow.com/questions/58282436/is-it-possible-to-use-mat-select-and-mat-chips-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!