Home > Enterprise >  Angular get items value in ngFor
Angular get items value in ngFor

Time:04-03

Currently im iterating through cart.items. Each item has owner's username and i want to display the owner's username and his products that i have purchased. Problem is i can only iterate through cart.items and not by owner's username so im getting duplicate cart items.

Im actually passing item from parent ngFor to child so i can get items.username.

Parent html:

<ng-container *ngIf="cart.items.length">
    <div *ngFor="let item of cart.items">
        <chlid-component [item]="item"></child-component>
    </div>
</ng-container>

Im getting cart.items from my cartService.

child-component.component:

@Input() item: ICartItem;
username: string;

getUser() {
    const user = this.userService.getUser(this.item.user).subscribe(
      (user: IUser) => {
        this.username = user.username;
        this.userImage = user.image;
      }
    )
  }

chlid-component.html:

<ng-container *ngIf="(cart$ | async) as cart">
    <div >
        <div  routerLink="/users/{{username}}">{{username}}</div>
    </div>
<ng-container *ngFor="let item of cart.items">
    <div  *ngIf="item.user == username">
        // some code here
    </div>               
</ng-container>

im getting username from parent's item to list item's that i bought from owner. But there is problem that i can buy multiple items from owner so it displays owner's items twice. i.e

User-1:    User-1:   User-2:
item1,     item1,    item3
item2,     item2

In child-component i'm trying to pass ngFor value to hashset and check if that username already exit's in there. How can i get item.username value and pass it to hashSet and is there a proper way to achieve that. I checked console.log and got hundreds of response for just 3 items. Can you suggest a proper way to achieve that?

CodePudding user response:

Ok, to make it running according to your needs I had to group the items by username and them I used the KeyValue pipe on the ngFor, you can read about it here https://angular.io/api/common/KeyValuePipe

here is the updated stackblitz

to group the items

 this.cart.items.forEach((item) => {
  if (!this.groupedItems[item.username]) {
    this.groupedItems[item.username] = [];
  }
  this.groupedItems[item.username].push(item);
});

and the display

<div *ngFor="let group of groupedItems | keyvalue">
  <div >
    <div >{{ group.key }}</div>
  </div>

  <div *ngFor="let item of group.value">
    <app-child [item]="item"></app-child>
  </div>
</div>
  • Related