![](/img/trans.png)
[英]Current selected value in angular6 material mat-selection-list
[英]Remove selected items from Angular Material mat-selection-list
我需要能够从 Angular 材料列表中删除选定的项目。 为此,我决定从最初的项目数组中减去选定项目的数组(不确定这是最好的方法)。
我的问题是我找不到将选定项目数组从 HTML 传递到 TS 并使用它的方法。
Angular Material 在其文档中有以下示例:
{{x.selectedOptions.selected.y}}
其中 x 是 mat-selection-list 选择器的 ID,y 是您对选定元素所做的事情。 但这似乎仅在 HTML 中有效。
下面是我的代码不起作用。
HTML 在这里我设置了列表和应该触发删除 function 的按钮。
<mat-selection-list #apps>
<mat-list-option *ngFor="let app of appList" [value]="app">
{{app}}
</mat-list-option>
</mat-selection-list>
<button
class='remove-button'
(click)="deleteSelected()"
mat-stroked-button color="primary">
Remove from list
</button>
TS 我试图弄乱选定的选项,但它显然不起作用,因为 selectedOptions 被声明为字符串数组并且没有“selected”方法。 我知道这是一个愚蠢的尝试,但无论如何,找不到更好的方法:) 应该有一种方法可以将选定的元素作为数组传递给 TS...
export class SubscriptionListComponent implements OnInit {
selectedOptions: string[]
appList: string[] = ['Instagram', 'Facebook', 'Telegram', 'WhatsApp', 'GitHub']
deleteSelected() {
this.appList.filter(x => !this.selectedOptions.selected.includes(x))
}
目标是在单击按钮时修改 appList,以便从中删除所选元素并且也不显示在列表中。
对于那些可能面临同样挑战的人,我发布了对我有用的代码,并且完全符合我的要求(单击时从列表中删除选定的元素)。
HTML 与上述相同。
TS:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatSelectionList } from '@angular/material/list';
@Component({
selector: 'app-subscription-list',
templateUrl: './subscription-list.component.html',
styleUrls: ['./subscription-list.component.scss']
})
export class SubscriptionListComponent implements OnInit {
@ViewChild('apps') selectionList: MatSelectionList
appList: string[] = ['Instagram', 'Facebook', 'Telegram', 'WhatsApp', 'GitHub']
deleteSelected() {
var selected: string[] = this.selectionList.selectedOptions.selected.map(s => s.value)
var diff = this.appList.filter(el => !selected.includes(el))
this.appList = diff
}
constructor() { }
ngOnInit(): void {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.