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

Angular Material多选动态设置mat-option选中状态的方法

在Angular Material的mat-select多选组件中动态控制选项选中状态

没问题,我来帮你搞定这个需求!其实Angular Material的mat-select多选模式下,选项的选中状态是由绑定的ngModel数组来控制的,而不是直接给mat-option加checked属性。不过我们可以通过你的users数组里的checked字段来初始化或同步选中状态,具体做法如下:

核心思路

当mat-select开启multiple模式时,[(ngModel)]绑定的是所有选中选项的value集合。所以我们需要:

  • 初始化时,把users数组中checked: true的用户对象加入到bookform.users数组中;
  • 模板中给每个mat-option绑定对应的用户对象作为value,这样mat-select会自动匹配bookform.users里的对象,标记为选中状态。

具体实现代码

组件类代码

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

@Component({
  selector: 'app-user-select',
  templateUrl: './user-select.component.html',
  styleUrls: ['./user-select.component.css']
})
export class UserSelectComponent implements OnInit {
  users = [
    { name: 'name1', checked: true },
    { name: 'name2', checked: false },
    { name: 'object3', checked: true }
  ];
  bookform!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    // 初始化表单,同时根据users的checked字段填充选中的用户
    this.bookform = this.fb.group({
      users: [this.users.filter(user => user.checked)]
    });
  }

  // 如果你需要手动同步checked字段和选中状态,可以加这个方法
  syncCheckedStatus() {
    this.bookform.get('users')?.setValue(this.users.filter(user => user.checked));
  }
}

模板代码

<mat-select 
  placeholder="users" 
  multiple 
  [(ngModel)]="bookform.value.users" 
  name="data_scientists"
  [formControl]="bookform.get('users')"
>
  <mat-option 
    *ngFor="let user of users" 
    [value]="user"
  >
    {{ user.name }}
  </mat-option>
</mat-select>

关键说明

  • 不要直接给mat-option设置checked属性,因为这会和mat-select的ngModel状态脱离同步,导致交互时出现异常。
  • 如果后续你需要修改users数组里的checked字段并同步到选中状态,可以调用上面的syncCheckedStatus()方法,或者使用RxJS监听users的变化自动同步。
  • 确保mat-option的[value]绑定的是完整的用户对象(而不是只绑定name),这样mat-select才能正确匹配选中项。

这样就能完美实现根据users数组里的checked字段动态控制选项的选中状态啦!

内容的提问来源于stack exchange,提问作者El Fadel Anas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:27:02