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

Angular Material:如何基于下拉选择显示对应过滤器div

实现Angular Material下拉选择对应显示过滤器的功能

步骤1:完善组件类与过滤器数据结构

首先确保你的filters数组每个元素包含唯一标识字段(比如key),用来关联对应的过滤器。同时在组件类中定义变量存储选中的过滤器:

// 组件类示例
filters = [
  { showValue: 'supplier.supplierName', key: 'supplierName' },
  // 可添加其他过滤器选项...
];
selectedFilter: any; // 存储选中的过滤器对象

步骤2:修改下拉框代码,绑定选中值

给mat-select添加双向绑定,获取用户选中的过滤器选项:

<mat-form-field>
  <mat-label>{{ 'supplier.showFilters' | translate }}</mat-label>
  <mat-select [(ngModel)]="selectedFilter">
    <mat-option *ngFor="let filter of filters" [value]="filter">
      {{filter.showValue | translate}}
    </mat-option>
  </mat-select>
</mat-form-field>

步骤3:修改过滤器的显示条件

将每个过滤器的*ngIf条件改为判断选中过滤器的标识是否匹配当前过滤器:

<!-- 供应商名称过滤器 -->
<div class="col-2" *ngIf="selectedFilter?.key === 'supplierName'">
  <mat-form-field>
    <mat-label>{{ 'supplier.supplierName' | translate }}</mat-label>
    <input formControlName="companyName" matInput/>
  </mat-form-field>
</div>

<!-- 其他过滤器示例 -->
<div class="col-2" *ngIf="selectedFilter?.key === 'otherFilterKey'">
  <!-- 对应过滤器内容 -->
</div>

可选:使用响应式表单控件替代ngModel

如果组件使用响应式表单,也可以用FormControl绑定选中值:

// 组件类中定义表单控件
filterSelectControl = new FormControl();
<mat-select [formControl]="filterSelectControl">
  <!-- 选项代码不变 -->
</mat-select>

此时过滤器的*ngIf条件改为:

*ngIf="filterSelectControl.value?.key === 'supplierName'"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:55:13