【问题标题】:angular mat-select, select all using Boolean function?角度垫选择,使用布尔函数选择所有?
【发布时间】:2026-01-17 03:50:02
【问题描述】:

我们如何使用布尔函数在角度 mat-select 中实现全选。 不使用表单标签和表单生成器。

组件.html

<div layout="column" class="mat-cloumn w-25">
  <mat-form-field appearance="fill">
    <mat-label>Location</mat-label>
    <mat-select class="user-control" multiple>
      <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
      <mat-option  [value]="store.id" *ngFor="let store of stores">{{ store.name }}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

组件.ts

  notSelectedAll = true;

  stores = [
    {id:1,name:'store - 1'},
    {id:2,name:'store - 2'},
    {id:3,name:'store - 3'},
    {id:4,name:'Store - 4'}
  ];

toggleAllSelection(){
  if(this.notSelectedAll = !this.notSelectedAll){
    console.log(false)
  }else{
    console.log(true)
  }
}

我们如何在 angular mat-select 中实现全选

【问题讨论】:

  • 您好,只是问一下,您检查过这个答案*.com/questions/51580095/… 吗?
  • 我已经用材料做了同样的事情,我必须模拟一个代表值'Check all'的mat选项的假值,全局我已经做了一些事情类似于这个答案,这有帮助吗?如果您需要,我很确定以后可以写一个很好的答案
  • 我正在努力,我想这可能是你想要的? stackblitz.com/edit/…
  • 可以肯定的是,您使用模板驱动的表单或反应式表单或仅使用一个formControl,如果只是一个formControl,以模板驱动的方式还是反应式的方式?
  • 感谢您的编辑,我认为您离解决方案不远,只需在.ts 中添加一个变量,如果使用得当,MatSelect 的值应该可以映射,我'我会试着在 1 或 2 小时内给出我的答案

标签: angular typescript


【解决方案1】:

所以问题是 MatSelect 启用了多个, 接受一个值数组,

如果您想通过单击一个来切换AllNode, 你必须调用一个函数来设置 MatSelect 中的所有值, 这就是为什么你需要另一个变量

这是你的模板

 <mat-form-field appearance="fill">
 <mat-select [value]='value' class="user-control" multiple>
    <mat-option #allSelected (click)="toggleAllSelection()" [value]="0">All</mat-option>
    <mat-option [value]="store.id" *ngFor="let store of stores"
(click)="valueChange(store.id)" >{{ store.name }}</mat-option>
</mat-select>

还有.ts

export class AppComponent {

   value = [];

   selectAll = false;

   stores = [
     { id: 2, name: "store - 1" },
     { id: 3, name: "store - 2" },
     { id: 4, name: "store - 3" },
     { id: 5, name: "Store - 4" }
   ];

  constructor(private fb: FormBuilder) {}

  ngOnInit() {}

  // Function used to properly bind the values on 1 MatOption
  valueChange(id: number) {
  if (this.value.indexOf(id) > -1) {
  //find the index of the element to delete if present
  const pos = this.value.indexOf(id);
  this.value.splice(pos, 1);
  } else {
  // else you push the selected value
  this.value.push(id);
 }
}
  //function to select of deselect All
  toggleAllSelection() {
  this.selectAll = !this.selectAll;
  console.log(this.selectAll);
  if (this.selectAll == true) {
    this.value = [0, 2, 3, 4, 5];
  } else {
    this.value = [];
   }
 }
}

(在缺少单个值的函数后编辑)。

由于您根本不使用 Angular 的任何形式, 您需要手动处理所有操作,以使值在 MatSelect 和图形输出之间正确通信。

这里的value用来保存选中Node的结果, 但也可以通过在 mat-form-field 的模板中传递它, 它允许 MatSelect 正确检查相应的 MatOptions

更新堆栈闪电战的链接: https://stackblitz.com/edit/angular-material-with-angular-v5-3arsoh?file=app/app.component.html

如果您不想使用 FormGroup 或 FormBuilder,我仍然认为仅使用 formControl 可以减少代码。

【讨论】: