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

如何实现mat-list点击关闭按钮删除对应列表项?

解决方案

mat-list 是否支持删除功能?

mat-list 本身只是UI展示组件,不直接提供删除功能,但它是数据驱动的——只要你修改绑定的数据源,Angular的变更检测会自动更新视图,实现条目删除的效果。核心是通过操作你的jsonData来删除对应条目,视图会同步更新。


实现步骤

1. 修改HTML模板,完善点击事件绑定

给父项的关闭按钮添加点击事件,同时给子项的点击事件补充必要的定位参数(父项key、子项分组key):

<mat-list >
  <ng-container *ngFor='let item of jsonData| keyvalue ;'>
    <mat-list-item>
      <h3 matLine class='parent-title'> {{item.key}}</h3>
      <!-- 父项关闭按钮绑定删除方法 -->
      <mat-icon (click)="removeParent(item.key)">close</mat-icon>
      <div>
        <mat-divider></mat-divider>
      </div>
    </mat-list-item>
    <ng-container *ngFor='let child of $any(item.value)'>
      <ng-container *ngFor='let subChild of child | keyvalue'>
        <ng-container *ngFor='let value of $any(subChild.value)'>
          <mat-list-item>
            <h3 matLine class='child-title'> {{ value }}</h3>
            <!-- 子项关闭按钮传递父key、子分组key、当前值 -->
            <mat-icon (click)='removeChild(item.key, subChild.key, value)'>close</mat-icon>
          </mat-list-item>
        </ng-container>
      </ng-container>
    </ng-container>
  </ng-container>
</mat-list>

2. 在组件TS文件中实现删除逻辑

添加两个方法分别处理父项和子项的删除,直接修改jsonData数据源:

import { Component } from '@angular/core';

@Component({
  // 你的组件元数据(如selector、templateUrl等)
})
export class YourComponent {
  jsonData: any = {
    "Parent1": [
        {
            "Data1": [
                "Item1",
                "Item2"
            ]
        }
    ],
    "Parent2": [
        {
            "Data2": [
                "Item3",
                "Item4"
            ]
        }
    ]
  };

  // 删除父项
  removeParent(parentKey: string): void {
    delete this.jsonData[parentKey];
    // 若组件使用OnPush变更检测策略,需手动触发:
    // this.cdr.markForCheck();
  }

  // 删除子项
  removeChild(parentKey: string, childGroupKey: string, itemValue: string): void {
    // 定位到目标子项数组
    const childArray = this.jsonData[parentKey][0][childGroupKey];
    if (childArray) {
      // 过滤掉要删除的条目
      this.jsonData[parentKey][0][childGroupKey] = childArray.filter(item => item !== itemValue);
      
      // 可选:如果子项数组为空,自动删除对应的父项
      if (this.jsonData[parentKey][0][childGroupKey].length === 0) {
        delete this.jsonData[parentKey];
      }
    }
  }
}

关键说明

  • 数据驱动视图:Angular会监听jsonData的变化,当你删除数组元素或对象属性后,mat-list会自动重新渲染,隐藏被删除的条目。
  • 类型优化:如果项目严格要求类型安全,可以给jsonData定义接口替代$any断言,示例:
    interface ParentItem {
      [key: string]: string[];
    }
    
    interface JsonData {
      [key: string]: ParentItem[];
    }
    
    jsonData: JsonData = { /* 你的数据 */ };
    
  • 变更检测:若组件使用ChangeDetectionStrategy.OnPush,需注入ChangeDetectorRef并在删除后调用this.cdr.markForCheck()手动触发更新。

内容的提问来源于stack exchange,提问作者arj

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:55:17