我想知道是否有可能混合使用mat-select和mat-chip-list。在chip-list中,我想显示从mat-select中选择的选项。
如果是,我该怎么做呢?
发布于 2020-02-11 19:51:54
是的,这是可能的。您需要在<mat-select>中使用<mat-select-trigger>。Inside <mat-select-trigger> place <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);
}
}
}Here is a complete example with Angular Material 9, but it works the same in version 6.
我希望这能帮到你!

发布于 2019-10-08 22:05:05
您可以通过将选定的值压入一个变量并在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[] = [];
}发布于 2021-05-23 21:16:39
https://stackoverflow.com/questions/58282436
复制相似问题