![](/img/trans.png)
[英]Remove selected items from Angular Material mat-selection-list
[英]Getting list of selected values from Angular 6 mat-selection-list
如何获取从组件中的 Angular 材料垫选择列表中选择的所有值的列表。 给出的示例显示了要显示在模板中而不是组件中的值。 我正在尝试修改此问题中给出的解决方案,但它对我不起作用。 这是我当前的代码:
模板:
<mat-selection-list #selected [(ngModel)]="readingTypesSelected" (ngModelChange)="onSelection($event)" >
<mat-list-option *ngFor="let readingType of readingTypes">
{{readingType.name}}
</mat-list-option>
</mat-selection-list>
成分:
onSelection(e, v) {
console.log(e);
console.log(v);
}
以下内容被记录到控制台:
我如何从中提取所选选项的实际值?
解决方案:
模板代码的前两行应该是(如已接受解决方案中的 stackblitz 链接所示):
<mat-selection-list #selected (selectionChange)="onSelection($event, selected.selectedOptions.selected)" >
<mat-list-option *ngFor="let readingType of readingTypes" [value] ="readingType">
尝试这个
<mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)">
<mat-list-option *ngFor="let shoe of typesOfShoes" [value]="shoe">
{{shoe}}
</mat-list-option>
</mat-selection-list>
绑定[(ngModel)]="selectedOptions"
您可以在组件中使用selectedOptions
变量,该变量将包含所有选定的项目。
这个解决方案更好
selectionChanged(event: MatSelectionListChange): void {
this.selected = event.options.filter(o => o.selected).map(o => o.value);
}
在您的代码值属性丢失
代替
<mat-list-option *ngFor="let readingType of readingTypes">
和
<mat-list-option *ngFor="let readingType of readingTypes" [value]="readingType">
然后在 readingTypesSelected 中获取选定的数组,
[(ngModel)]="readingTypesSelected" 中提到了 readingTypesSelected
我在这里更新了你的 stackblitz 代码https://angular-selection.stackblitz.io
现在您可以在控制台中获取选定的值。
<mat-selection-list #products [(ngModel)]="selectedProducts">
<mat-list-option *ngFor="let eachProduct of allProducts;" [value]="eachProduct">
{{eachProduct.name}}
</mat-list-option>
</mat-selection-list>
{{selectedProducts|json}}
在 Angular 10 中测试。主要部分是[value]="eachProduct"
否则它将显示为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.