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

Angular15测试用例运行报错:mat-chip-grid需搭配matChipInputFor使用求解决

解决Angular 15中"mat-chip-grid must be used in combination with matChipInputFor"错误

问题原因

mat-chip-grid是Angular Material专为支持添加新芯片的交互场景设计的组件,它必须配合matChipInputFor指令绑定输入框,才能实现芯片添加功能。如果只是单纯展示已有芯片列表,应该使用mat-chip-list组件。

解决方案

情况1:仅展示已有芯片

直接将mat-chip-grid替换为mat-chip-list即可,修改后的代码:

<mat-chip-list>
    <mat-chip-row highlighted *ngFor="let color of colors">
        {{color.name}}
    </mat-chip-row>
</mat-chip-list>

情况2:需要支持添加新芯片

如果确实要使用mat-chip-grid实现可添加功能,必须搭配输入框并通过matChipInputFor建立绑定,示例代码:

<mat-form-field appearance="fill">
    <mat-label>添加颜色</mat-label>
    <!-- 输入框通过matChipInputFor绑定到mat-chip-grid的模板引用 -->
    <input matInput 
           [matChipInputFor]="chipGrid" 
           [matChipInputSeparatorKeyCodes]="[ENTER, COMMA]"
           (matChipInputTokenEnd)="addColor($event)">
    
    <mat-chip-grid #chipGrid>
        <mat-chip-row 
            highlighted 
            *ngFor="let color of colors" 
            (removed)="removeColor(color)">
            {{color.name}}
            <button matChipRemove>
                <mat-icon>cancel</mat-icon>
            </button>
        </mat-chip-row>
    </mat-chip-grid>
</mat-form-field>

同时需在组件类中实现对应的添加/移除逻辑:

import { ENTER, COMMA } from '@angular/cdk/keycodes';
import { MatChipInputEvent } from '@angular/material/chips';

// 组件类内定义
separatorKeysCodes: number[] = [ENTER, COMMA];
colors: {name: string}[] = [];

addColor(event: MatChipInputEvent): void {
  const value = (event.value || '').trim();
  if (value) {
    this.colors.push({name: value});
  }
  event.chipInput!.clear();
}

removeColor(color: {name: string}): void {
  const index = this.colors.indexOf(color);
  if (index >= 0) {
    this.colors.splice(index, 1);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:57:42