我需要能够从角度材料列表中删除选定的项目。为此,我决定从初始项数组中减去选定项的数组(不确定这是最好的方法)。
我的问题是,我找不到一种方法来将所选项目的数组从HTML传递到TS并处理它。
Angular Material的文档中包含以下示例:
{{x.selectedOptions.selected.y}}
其中x是mat- selector list选择器的ID,y是对所选元素执行的操作。但这似乎只在HTML中有效。
下面是我的代码,它不能工作。
在HTML中,我设置了列表和触发删除功能的按钮。
<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>
在这里我试图打乱所选的选项,但显然行不通,因为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,这样选定的元素就会从其中删除,并且不会显示在列表中。
发布于 2020-12-30 18:13:30
对于那些可能面临同样挑战的人,我发布了对我有效的代码,并且完全按照我想要的做了(单击时从列表中删除选定的元素)。
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 {
}
}
https://stackoverflow.com/questions/65496858
复制相似问题