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

Angular Material两组Chip列表如何实现双向联动并接入表单

核心解决思路

以同一个FormControl作为唯一的状态数据源,所有选中状态的判断和修改都基于该控件的值,避免两边状态独立存储导致的不同步。


完整修改代码

TS文件

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-skills',
  templateUrl: './skills.component.html',
  styleUrls: ['./skills.component.css']
})
export class SkillsComponent {
  // 改为普通数组更适合ngFor遍历
  development = ["React", "Redux", "Webpack", "Javascript", "SCRUM","C#", "Docker"];
  // 多选Chip的控件初始值为空数组
  devControl= new FormControl([]);
  chipsValue$ = this.devControl.valueChanges;

  // 统一的选中状态切换方法,左右两侧Chip点击都调用该方法
  toggleOption(option: string) {
    const currentValue = this.devControl.value as string[];
    if (currentValue.includes(option)) {
      // 已选中则从列表中移除
      this.devControl.setValue(currentValue.filter(item => item !== option));
    } else {
      // 未选中则添加到列表
      this.devControl.setValue([...currentValue, option]);
    }
  }
}

HTML文件

<div class="column">
  <mat-chip-list selectable multiple [formControl]="devControl">
    <mat-chip #chip="matChip" (click)="toggleOption(option)"
      *ngFor="let option of development"
      [selected]="devControl.value?.includes(option)"
      [value]="option">
      <mat-icon *ngIf="chip.selected">clear</mat-icon>
      {{option}}
    </mat-chip>
  </mat-chip-list>
  <div>Value: {{chipsValue$ | async}}</div>
</div>
<div class="column">
  <mat-chip-list selectable multiple>
    <!-- 右侧仅遍历已选中的选项 -->
    <mat-chip #chip="matChip" (click)="toggleOption(option)"
      *ngFor="let option of devControl.value"
      [selected]="true"
      [value]="option">
      <mat-icon>clear</mat-icon>
      {{option}}
    </mat-chip>
  </mat-chip-list>
</div>

关键改动说明

  • 修复了左侧Chip的[selected]绑定逻辑:原来直接绑定option字符串,只要非空就永远为true,现在改为判断当前选项是否在FormControl的选中数组中
  • 移除了右侧Chip列表对FormControl的重复绑定:右侧仅展示已选中的选项,默认就是选中状态,点击直接触发移除逻辑即可
  • 统一状态修改入口:所有Chip的点击操作都调用同一个toggleOption方法修改FormControl的值,两边状态会自动同步
  • 表单收集选中值时直接取devControl.value即可,符合表单使用规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:57:04