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

如何让mat-select默认选中所有选项?

解决mat-select多选默认全选的问题

你直接给mat-option加[selected]="true"不生效,是因为mat-select在多选模式下,选中状态是由组件自身的value(或ngModel)控制的,单个选项的[selected]会被组件内部状态覆盖,所以单独设置没用。

正确的做法是:

  • 在组件类里定义一个数组,用来存储所有选中的选项值
  • 初始化时把所有questionId都塞进这个数组
  • 把mat-select和这个数组绑定

修改后的模板代码

<mat-form-field appearance="outline">
  <mat-label>Questions ({{selectedQuestions.length}} of {{structureViewObj.records[0].questions.length}})</mat-label>
  <mat-select 
    multiple 
    [(ngModel)]="selectedQuestions" 
    (selectionChange)="selectQue($event.value)"
  >
    <mat-option 
      *ngFor="let item of structureViewObj.records[0].questions"
      [value]="item.questionId"
    >{{item.label}}</mat-option>
  </mat-select>
</mat-form-field>

组件类代码示例

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

@Component({
  // 你的组件元数据
})
export class YourComponent implements OnInit {
  selectedQuestions: number[] = []; // 假设questionId是数字类型,可根据实际类型调整
  structureViewObj: any; // 你的数据对象

  ngOnInit(): void {
    // 页面初始化时,把所有questionId加入选中数组
    if (this.structureViewObj?.records[0]?.questions?.length) {
      this.selectedQuestions = this.structureViewObj.records[0].questions.map(item => item.questionId);
      // 如果需要保留原有questionSelected变量,可在此赋值
      // this.questionSelected = this.selectedQuestions.length;
    }
  }

  selectQue(selectedValues: number[]) {
    this.selectedQuestions = selectedValues;
    // 这里保留你原有业务逻辑,比如更新选中数量
    // this.questionSelected = selectedValues.length;
  }
}

说明:

  • 用[(ngModel)]双向绑定选中数组,默认选中和用户后续选择都会自动同步
  • 模板里的选中数量可以直接用selectedQuestions.length代替,省去单独维护questionSelected变量的麻烦(如果原有逻辑有特殊处理,也可以在selectionChange事件里更新)
  • 如果structureViewObj是异步请求加载的数据,要确保在数据加载完成后再给selectedQuestions赋值,比如放在请求的回调或subscribe里

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:27:09