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

如何在ngOnInit阶段为Angular Material chips关联的Set和FormControl填充初始值

问题根因

你目前的报错来自两个API使用错误,以及模板的选中状态配置冲突:

  • Set 数据结构没有push方法,添加元素需使用add()方法
  • FormControl 本身不是数组,没有push方法,多选芯片绑定的FormControl值是选中项数组,直接赋值即可
  • 模板中mat-chip写死[selected]="false"会覆盖表单的自动选中逻辑,需要移除

修正后的组件类代码

export class EventPlanningComponent implements OnInit {

  allServices: ServiceDto[];

  keywords = new Set<string>(); // 提前指定泛型更严谨
  formControl = new FormControl<string[]>([]); // 多选芯片值为字符串数组类型

  constructor(
    private readonly serviceService: ServiceService
  ) { }

  async ngOnInit(): Promise<void> {
    await this.initServices();
  }

  async initServices(): Promise<void> {
    this.allServices = await this.serviceService.getAllServices().toPromise();
    const defaultSelected: string[] = [];

    for (const service of this.allServices) {
      this.keywords.add(service.name); // 用add方法给Set添加元素
      if (service.default === true) {
        defaultSelected.push(service.name);
      }
    }
    // 批量给FormControl赋值默认选中项
    this.formControl.setValue(defaultSelected);
  }

  removeKeyword(keyword: string) {
    this.keywords.delete(keyword);
    // 移除选项同时更新表单值,避免残留无效选中项
    const currentValue = this.formControl.value || [];
    this.formControl.setValue(currentValue.filter(item => item !== keyword));
  }
}

修正后的模板代码

只需移除mat-chip上写死的[selected]="false"即可,表单会自动管理选中状态:

<mat-form-field class="chip-list" appearance="fill">
  <mat-label>Dienste auswählen</mat-label>
  <mat-chip-list #chipList aria-label="Dienste auswählen" multiple [formControl]="formControl">
    <mat-chip *ngFor="let keyword of keywords" [value]="keyword">
      {{keyword}}
    </mat-chip>
  </mat-chip-list>
</mat-form-field>
<p>
  <b>The following keywords are selected:</b> {{formControl.value}}
</p>

实现效果

修改后可满足需求:

  • 初始化时自动加载所有可选芯片选项
  • 默认选中标记为default=true的服务
  • 表单值自动同步当前选中的所有芯片内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:24:00