You need to enable JavaScript to run this app. Angular 如何实现从ngFor列表中获取用户选中的类别值
优惠活动
大模型
产品
解决方案
定价
更多

Angular 如何实现从ngFor列表中获取用户选中的类别值

原代码核心问题

修正方案

摒弃依赖DOM属性传值的思路,直接把循环对应的分类值作为事件参数传入,从根源上保证取值稳定:

修改后的HTML模板

<ng-container *ngFor="let part of partsList">
  <a 
    class="list-group-item list-group-item-action"
    (click)="onCategorySelect(part.Category)"
  >
    {{ part.Category }}
  </a>
</ng-container>

修改后的TS代码

partsList: Parts[] = [];
selectedCategory: Parts[] = [];

constructor(private ApiService: ApiService) {}

ngOnInit() {
  this.ApiService.getParts().subscribe(data => {
    this.partsList = data;
  });
}

onCategorySelect(selectedValue: string) {
  this.selectedCategory = this.partsList.filter(item => item.Category === selectedValue);
}

实现说明


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 15:36:01