如何将mat-select下拉复选框状态双向绑定至TS变量checks?
解决方案
1. 修改TypeScript文件
更新组件类,实现checks数组与多选框选中状态的双向同步:
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'select-overview-example', templateUrl: 'select-overview-example.html', styleUrls: ['select-overview-example.css'], }) export class SelectOverviewExample implements OnInit { options = ['one', 'two', 'three', 'four', 'five']; checks: boolean[] = [true, true, false, false, true]; selected = new FormControl([]); ngOnInit() { // 初始化:根据checks数组设置默认选中项 const initialSelected = this.options.filter((_, idx) => this.checks[idx]); this.selected.setValue(initialSelected); // 监听选中状态变化,同步更新checks数组 this.selected.valueChanges.subscribe(selectedItems => { this.checks = this.options.map(item => selectedItems.includes(item)); }); } // 手动修改checks数组后,同步更新选中状态 syncChecksToSelection() { const selectedItems = this.options.filter((_, idx) => this.checks[idx]); this.selected.setValue(selectedItems); } }
2. 修改HTML模板
保持mat-select与FormControl绑定,确保选中状态和checks数组自动联动:
<mat-form-field appearance="fill"> <mat-label>Select multiple</mat-label> <mat-select [formControl]="selected" multiple> <mat-option *ngFor="let option of options; let i = index" [value]="option" > {{ option }} </mat-option> </mat-select> </mat-form-field> <!-- 可选:添加测试按钮验证手动修改checks的同步效果 --> <button (click)="checks[2] = !checks[2]; syncChecksToSelection()"> 切换第三个选项的checks状态 </button>
原理说明
- 初始化阶段,通过
checks数组筛选出对应索引为true的选项,赋值给FormControl,实现默认选中效果。 - 监听
FormControl的valueChanges事件,用户勾选/取消选项时,自动更新checks数组的对应值。 - 若手动修改
checks数组内容,调用syncChecksToSelection()方法即可同步下拉框的选中状态。
内容的提问来源于stack exchange,提问作者gnitsuk
相关产品推荐
相关产品推荐

