You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Angular Material Mat-Table选中行的外部按钮删除功能?

实现Angular Material Mat-Table选中行批量删除(外部按钮)

1. 组件类核心配置

在组件TS文件中导入必要模块,定义数据结构、数据源和选中行管理对象:

import { Component } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { SelectionModel } from '@angular/cdk/collections';

// 自定义数据接口,根据业务调整字段
interface TableItem {
  id: number;
  name: string;
  // 其他业务字段
}

@Component({
  selector: 'app-table-delete',
  templateUrl: './table-delete.component.html',
  styleUrls: ['./table-delete.component.css']
})
export class TableDeleteComponent {
  // 表格列名集合,必须包含多选列"select"
  displayedColumns: string[] = ['select', 'id', 'name'];
  // 原始数据集合
  tableData: TableItem[] = [
    { id: 1, name: '商品A' },
    { id: 2, name: '商品B' },
    { id: 3, name: '商品C' }
  ];
  // 表格数据源
  dataSource = new MatTableDataSource<TableItem>(this.tableData);
  // 选中行管理器,true表示支持多选
  selection = new SelectionModel<TableItem>(true, []);

  // 判断是否已全选
  isAllSelected(): boolean {
    const selectedCount = this.selection.selected.length;
    const totalCount = this.dataSource.data.length;
    return selectedCount === totalCount;
  }

  // 切换全选/取消全选
  masterToggle(): void {
    this.isAllSelected() 
      ? this.selection.clear() 
      : this.dataSource.data.forEach(row => this.selection.select(row));
  }
}

2. 模板(HTML)设置

添加外部删除按钮,并配置带多选功能的Mat-Table:

<!-- 外部删除按钮,无选中行时禁用 -->
<button 
  mat-raised-button 
  color="warn" 
  (click)="deleteSelectedRows()"
  [disabled]="selection.isEmpty()"
>
  删除选中行
</button>

<!-- Mat-Table 主体 -->
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
  <!-- 多选列定义 -->
  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef>
      <mat-checkbox 
        (change)="$event ? masterToggle() : null"
        [checked]="selection.hasValue() && isAllSelected()"
        [indeterminate]="selection.hasValue() && !isAllSelected()"
      ></mat-checkbox>
    </th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox 
        (click)="$event.stopPropagation()"
        (change)="$event ? selection.toggle(row) : null"
        [checked]="selection.isSelected(row)"
      ></mat-checkbox>
    </td>
  </ng-container>

  <!-- ID列 -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let row"> {{ row.id }} </td>
  </ng-container>

  <!-- 名称列 -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> 名称 </th>
    <td mat-cell *matCellDef="let row"> {{ row.name }} </td>
  </ng-container>

  <!-- 表头和行渲染 -->
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;" (click)="selection.toggle(row)"></tr>
</table>

3. 实现删除逻辑

在组件类中添加deleteSelectedRows方法,支持纯前端数据更新或结合后端接口:

仅前端数据删除

deleteSelectedRows(): void {
  // 获取选中行的ID集合
  const selectedIds = this.selection.selected.map(row => row.id);
  // 过滤掉选中行,更新原始数据和数据源
  this.tableData = this.tableData.filter(item => !selectedIds.includes(item.id));
  this.dataSource.data = this.tableData;
  // 清空选中状态
  this.selection.clear();
}

结合后端接口删除

如果需要调用后端API,调整方法如下:

// 先导入自定义数据服务
import { YourDataService } from '../your-data.service';

// 组件类中注入服务
constructor(private dataService: YourDataService) {}

deleteSelectedRows(): void {
  const selectedIds = this.selection.selected.map(row => row.id);
  // 调用后端删除接口
  this.dataService.deleteItems(selectedIds).subscribe({
    next: () => {
      // 接口调用成功后更新前端数据
      this.tableData = this.tableData.filter(item => !selectedIds.includes(item.id));
      this.dataSource.data = this.tableData;
      this.selection.clear();
    },
    error: (error) => {
      // 处理删除失败场景,比如提示用户
      console.error('删除失败:', error);
    }
  });
}

关键说明

  • SelectionModel是Angular CDK提供的选中状态管理工具,支持单选/多选配置;
  • 外部按钮通过selection.isEmpty()判断是否禁用,避免无效操作;
  • 行点击事件绑定selection.toggle(row),支持点击整行切换选中状态;
  • 全选checkbox通过indeterminate属性处理部分选中的中间状态。

内容的提问来源于stack exchange,提问作者Mustafa ÇAMLICA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:30:44