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

Angular中如何隐藏下拉框已选中的选项?

完全可行,实现方案如下

核心逻辑

监听下拉框的选中值变化,动态过滤掉已选中的选项,只展示未被选择的动物。我们需要保留原始的动物数据列表,同时维护一个实时更新的过滤后列表用于渲染下拉选项。

修正并完善后的TS代码

首先修正ngOninit的拼写错误(应为ngOnInit),然后添加表单控件监听和过滤逻辑:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { AnimalDTO } from './your-path'; // 替换为实际文件路径
import { AnimalSVC } from './your-service-path'; // 替换为实际服务路径

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html'
})
export class YourComponent implements OnInit {
  animalObj: AnimalDTO;
  animalDS: any[] = []; // 存储从接口获取的原始动物列表
  filteredAnimals: any[] = []; // 动态过滤后的可选列表
  animalForm = new FormGroup({
    animal: new FormControl(null)
  });

  constructor(private animalSVC: AnimalSVC) {}

  ngOnInit() {
    this.getList();
    // 监听选中值变化,实时过滤可选列表
    this.animalForm.get('animal')?.valueChanges.subscribe(selectedId => {
      this.filteredAnimals = this.animalDS.filter(animal => animal.id !== selectedId);
    });
  }

  getList() {
    this.animalSVC.getListOfAnimal().subscribe((response: AnimalDTO) => {
      this.animalObj = response;
      this.animalDS = this.animalObj.items;
      // 初始化过滤列表为全部原始数据
      this.filteredAnimals = [...this.animalDS];
    });
  }
}

修改后的HTML代码

将下拉选项的遍历对象替换为过滤后的filteredAnimals,Angular Material的mat-select会自动保留已选中的选项文本在输入框中,即使该选项已从下拉列表移除:

<mat-form-field class="full-width" floatLabel="always" appearance="outline">
  <mat-label>Choose Animal</mat-label>
  <mat-select formControlName="animal">
    <mat-option *ngFor="let item of filteredAnimals" [value]="item.id">
      {{item.animal}}
    </mat-option>
  </mat-select>
</mat-form-field>

扩展说明

  • 如果需要支持多选,只需将FormControl改为FormControl([]),过滤逻辑调整为:
    this.filteredAnimals = this.animalDS.filter(animal => !selectedIds.includes(animal.id));
    
    同时给HTML中的mat-select添加multiple属性。
  • 也可以通过自定义管道实现模板内过滤,但组件内监听值变化的方式更便于后续扩展(比如添加重置逻辑、处理异步更新等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:05:24