首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >可以同时使用mat-select和mat-chips吗?

可以同时使用mat-select和mat-chips吗?
EN

Stack Overflow用户
提问于 2019-10-08 16:08:43
回答 3查看 9K关注 0票数 6

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

如果是,我该怎么做呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-02-11 19:51:54

是的,这是可能的。您需要在<mat-select>中使用<mat-select-trigger>。Inside <mat-select-trigger> place <mat-chip-list>

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

代码语言:javascript
复制
<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

代码语言:javascript
复制
@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.

我希望这能帮到你!

票数 20
EN

Stack Overflow用户

发布于 2019-10-08 22:05:05

您可以通过将选定的值压入一个变量并在mat-chip-list中读取该变量来完成此操作。

HTML:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
import {Component} from '@angular/core';

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

Stack Overflow用户

发布于 2021-05-23 21:16:39

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58282436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档