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

Angular 8中带mat-select-trigger的多选mat-select出现解析错误求解决

Angular 8中mat-select多选控件trigger模板语法错误的解决方案

问题场景

要添加带mat-select-trigger的多选mat-select控件,HTML代码如下:

<mat-tab label="DB Connection">
    <mat-form-field class="example-full-width">
        <mat-label>Database</mat-label>
        <mat-select [formControl]="types" multiple>
            <mat-select-trigger>
                {{types.value?.[0] || ''}}
                <span *ngIf="(types.value?.length || 0) > 1" class="example-additional-selection">
                    (+{{(types.value?.length || 0) - 1}} {{types.value?.length === 2 ? 'other' :
                    'others'}})
                </span>
            </mat-select-trigger>
            <mat-option *ngFor="let type of typeList" [value]="type">{{type}}</mat-option>
        </mat-select>
        <mat-icon matSuffix>storage</mat-icon>
    </mat-form-field>
</mat-tab>

运行后出现解析错误:

Parser Error: Unexpected token [, expected identifier or keyword at column 14 in [ {{types.value?.[0] || ''}} ] in ng:///AppModule/CommSettingsComponent.html@62:48 ("
[ERROR ->]<mat-option *ngFor="let type of typeList" [value]="type">{{type}}
"): ng:///AppModule/CommSettingsComponent.html@69:28, Directive MatOption

移除{{types.value?.[0] || ''}}行后错误消失。

环境版本:

  • Angular CLI: 8.3.29
  • Node: 14.17.6
  • OS: win32 x64
  • Angular: 8.2.14
  • @angular/material: 8.2.3

解决方案

Angular 8的模板解析器不支持**可选链?.后跟方括号索引[0]**的语法,这是Angular 9及以上版本才支持的特性,可通过以下方式修复:

方式1:改用条件判断替代

将types.value?.[0]替换为兼容Angular 8的条件写法:

{{ types.value ? types.value[0] : '' }}

方式2:在组件类中添加辅助方法

在组件的.ts文件中定义获取首个选中值的方法,避免模板中使用不兼容语法:

getFirstSelectedType(): string {
  return this.types.value?.length ? this.types.value[0] : '';
}

然后在模板中调用该方法:

{{ getFirstSelectedType() }}

方式3:升级Angular版本(可选)

若项目兼容,可升级至Angular 9及以上版本,原生支持?.[0]语法。升级前需确认第三方依赖是否适配新版本。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:33:21