Angular 2中使用Angular Material表格删除选中行的实现
解决Angular Material选中行删除问题
我来帮你搞定这个删除选中行的功能,你的代码里deleted方法的逻辑和语法都有问题,咱们一步步修正:
1. 修正删除方法的核心逻辑
替换你当前的deleted方法为以下代码,这是实现删除选中行的关键:
deleted($event) { // 过滤掉所有被选中的行,只保留未选中的数据 this.dataSource.data = this.dataSource.data.filter(row => !this.selection.isSelected(row)); // 清空选中状态,避免删除后残留选中标记 this.selection.clear(); }
代码说明:
- 使用
Array.filter()创建新数组,通过!this.selection.isSelected(row)筛选出未被选中的行 - 将新数组重新赋值给
this.dataSource.data,Angular Material表格会自动监听数据源变化并刷新界面 - 调用
this.selection.clear()清空选择状态,确保删除操作后没有残留的选中状态
2. 修正原有语法错误
你原来的deleted方法存在两处问题:一是误用delete操作符(它仅用于删除对象属性,不能处理数组元素),二是括号匹配错误。直接替换成上面的正确代码即可解决这些问题。
完整修正后的.ts文件
import {Component, ViewChild} from '@angular/core'; import {MatPaginator, MatTableDataSource} from '@angular/material'; import {SelectionModel} from '@angular/cdk/collections'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent { displayedColumns = ['select', 'num', 'name']; dataSource = new MatTableDataSource<Element>(ELEMENT_DATA); @ViewChild(MatPaginator) paginator: MatPaginator; ngAfterViewInit() { this.dataSource.paginator = this.paginator; } selection = new SelectionModel<Element>(true, []); isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.dataSource.data.length; return numSelected === numRows; } masterToggle() { this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row)); } deleted($event) { this.dataSource.data = this.dataSource.data.filter(row => !this.selection.isSelected(row)); this.selection.clear(); } } export interface Element { name: string; num: number; } const ELEMENT_DATA: Element[] = [ {num: 1, name: 'Message1'}, {num: 2, name: 'Message2'}, {num: 3, name: 'Message3'}, {num: 3, name: 'Message4'}, {num: 4, name: 'Message5'}, {num: 5, name: 'Message6'}, ];
现在点击「Remove Selected Messages」按钮,选中的行就会被成功删除,表格也会自动更新显示啦!
内容的提问来源于stack exchange,提问作者Heena
相关产品推荐
相关产品推荐

