如何在mat-optgroup外添加选项?无需手动创建或额外数组
问题描述
我们目前用mat-optgroup对mat-select里的大多数选项做分组,但有些选项不需要分组。能不能不用手动创建额外选项或数组来实现需求?
当前效果
- 显示一个无标题的分组,下方包含「Free Text Narrative」选项
- 「SNF/RNF」分组正常显示两个选项
- 空的「Home Health」分组也会显示
预期效果
- 「Free Text Narrative」选项直接显示,不归属任何分组
- 「SNF/RNF」分组正常显示两个选项
- 空的「Home Health」分组不显示
现有代码
HTML模板
<mat-form-field floatLabel="never"> <mat-select matNativeControl disableOptionCentering [(ngModel)]="selectedTemplate" (selectionChange)="validateTemplateFields(newImpressionDateRef.invalid)" placeholder="Select One"> <mat-option hidden [value] = "" selected>Select One</mat-option> <mat-optgroup *ngFor="let group of templateGroups" [label]="group.name"> <mat-option *ngFor="let template of group.templates" matTooltip="template.title" [value]="template.id"> {{template.title}} </mat-option> </mat-optgroup> </mat-select> </mat-form-field>
组件TS代码
templateGroups = [ { name: "", templates: [ { "id": this.clinicalImpressionPlanType, "title": 'Free Text Narrative', "disabled": false, "visible": true, }, ], }, { name: "SNF/RNF", templates: [ {"id": this.nomncType, "title": 'NOMNC (SNF/RNF)', "disabled": false, "visible": true, "TeamQueue": "SNF/RNF" }, {"id": this.icsType, "title": 'Initial Continued Stay', "disabled": false, "visible": true, "TeamQueue": "SNF/RNF" } ] }, { name: "Home Health", templates: [], } ]
解决方案
可以通过*ngIf和*ngFor的组合在模板内直接处理逻辑,不需要修改原数组或额外创建数组:
- 对空名称的分组,直接渲染内部的
mat-option,不使用mat-optgroup包裹 - 过滤掉无模板的空分组,只渲染有内容的分组
修改后的HTML模板代码:
<mat-form-field floatLabel="never"> <mat-select matNativeControl disableOptionCentering [(ngModel)]="selectedTemplate" (selectionChange)="validateTemplateFields(newImpressionDateRef.invalid)" placeholder="Select One"> <mat-option hidden [value] = "" selected>Select One</mat-option> <!-- 遍历所有分组,分情况渲染 --> <ng-container *ngFor="let group of templateGroups"> <!-- 渲染无分组的选项 --> <ng-container *ngIf="group.name === ''"> <mat-option *ngFor="let template of group.templates" matTooltip="template.title" [value]="template.id"> {{template.title}} </mat-option> </ng-container> <!-- 渲染有名称且非空的分组 --> <mat-optgroup *ngIf="group.name !== '' && group.templates.length > 0" [label]="group.name"> <mat-option *ngFor="let template of group.templates" matTooltip="template.title" [value]="template.id"> {{template.title}} </mat-option> </mat-optgroup> </ng-container> </mat-select> </mat-form-field>
这样做的优势:
- 保留原有
templateGroups数组结构,无需额外处理数据 - 所有逻辑在模板内完成,不用单独添加零散的
mat-option - 自动隐藏无内容的空分组
内容的提问来源于stack exchange,提问作者Jae
相关产品推荐
相关产品推荐

