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

Angular5中多个mat-selection-list的内置deselectAll方法失效问题

解决Angular 5中多个mat-selection-list的deselectAll方法失效问题

我来帮你搞定这个问题!在同一个组件里使用多个mat-selection-list时,核心是要正确关联每个列表的模板引用变量与组件类中的实例,这样才能精准调用对应的deselectAll()方法。下面是具体的解决步骤:

1. 组件类中通过@ViewChild获取列表实例

首先,在你的组件类里,使用@ViewChild装饰器,根据模板里的引用变量(#shoes和#cloths)获取对应的MatSelectionList实例。这样你就能在组件方法里直接操作每个列表了:

import { Component, ViewChild } from '@angular/core';
import { MatSelectionList } from '@angular/material/list';

@Component({
  selector: 'list-selection-example',
  templateUrl: 'list-selection-example.html',
})
export class ListSelectionExample {
  typesOfShoes = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];
  typesOfCloths = ['Shirts', 'Pants', 'Jackets', 'Sweaters', 'Dresses'];

  // 通过模板引用变量绑定列表实例
  @ViewChild('shoes') shoesList: MatSelectionList;
  @ViewChild('cloths') clothsList: MatSelectionList;

  // 取消所有鞋子的选择
  deselectShoes() {
    this.shoesList.deselectAll();
  }

  // 新增:取消所有衣物的选择
  deselectCloths() {
    this.clothsList.deselectAll();
  }
}

2. 更新模板,添加对应操作按钮

给衣物列表也添加一个取消选择的按钮,确保点击事件绑定到对应的组件方法:

Shoes:
<mat-selection-list #shoes>
  <mat-list-option *ngFor="let shoe of typesOfShoes" [value]="shoe">
    {{shoe}}
  </mat-list-option>
</mat-selection-list>
<button mat-button (click)="deselectShoes()">Deselect all Shoes</button>

<br><br>

Cloths:
<mat-selection-list #cloths>
  <mat-list-option *ngFor="let cloth of typesOfCloths" [value]="cloth">
    {{cloth}}
  </mat-list-option>
</mat-selection-list>
<button mat-button (click)="deselectCloths()">Deselect all Cloths</button>

3. 检查必要的依赖导入

别忘了确认你的NgModule中已经导入了MatListModule,否则mat-selection-list组件无法正常工作:

import { MatListModule } from '@angular/material/list';

@NgModule({
  imports: [
    // ...其他模块
    MatListModule
  ]
})
export class YourModule { }

问题根源说明

之前deselectAll()失效,大概率是因为你没有在组件类中正确获取到对应的列表实例,导致调用方法时找不到目标对象。通过@ViewChild绑定模板引用变量后,就能直接操作每个独立的mat-selection-list实例了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:14:01