获取用户从 ngFor 列表中选择的值

Get the value that a user selected from an ngFor list

这是我尝试让它工作的代码,但我可能只是做错了什么。

HTML:

<ng-container *ngFor='let parts of parts$'>
      <a class="list-group-item list-group-item-action" (click)="onCategorySelect($event)" value= "parts.Category">{{parts.Category}}</a>
    </ng-container>

.TS:

  parts$: Parts[];
  selectedCategory: Parts[];
  constructor(private ApiService:ApiService) { }

  ngOnInit() {
    return this.ApiService.getParts().subscribe(data => {this.parts$ = data});
  }

  onCategorySelect($x: any){
    this.selectedCategory = this.parts$.filter(element => element.Category === $x.target.value);
  }

我想获取用户选择的具体类别。

您可以像这样将给定值传入 click 函数

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

// 内部组件

onCategorySelect(category: any){
  this.selectedCategory = category;
}