You need to enable JavaScript to run this app. 如何基于isDefault布尔条件为列表内mat-select设置默认值
优惠活动
大模型
产品
解决方案
定价
更多

如何基于isDefault布尔条件为列表内mat-select设置默认值

解决方案

你可以直接通过Array.find()方法从当前行的templateNames数组中筛选出isDefault为true的模板对象,直接绑定给[value]即可,修改后的代码如下:

<ng-container matColumnDef="TEMPLATE">
    <th mat-header-cell *matHeaderCellDef> TEMPLATE
    </th>
    <td mat-cell *matCellDef="let element">
        <mat-select [value]="element.templateNames.find(template => template.isDefault)" (selectionChange)="addTemplateToLead($event)">
            <mat-option *ngFor="let template of element.templateNames" [value]="template">
                {{template.templateName}}
            </mat-option>
        </mat-select>
    </td>
</ng-container>

原理说明

因为你给mat-option绑定的[value]是完整的template对象,Angular Material的mat-select会自动匹配和[value]值相等的option作为默认选中项,直接筛选出符合条件的对象赋值即可。

可选优化

如果存在特殊场景可以做兼容处理:

  • 当可能存在多个isDefault=true的模板时,可调整为取第一个匹配项:
    [value]="element.templateNames.filter(t => t.isDefault)[0]"
    
  • 当没有默认模板时,可设置兜底选中第一个模板:
    [value]="element.templateNames.find(t => t.isDefault) ?? element.templateNames[0]"
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 15:15:07