[Fixed] Get the value that a user selected from an ngFor list

Issue

Here’s the code that I tried making it to work but I’m probably just doing something wrong.

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);
  }

I want to get the specific category that the user has selected.

Solution

You can just pass in the given value into the click function like so

<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>

// Inside component

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

Leave a Reply

(*) Required, Your email will not be published