0

How to perform search inside a nested loop of data

<span *ngFor="let like of post.likes" >
    <ion-icon name="heart" class="icons-heart" *ngIf="like.likedBy._id == userId; else elsehae" (click)="unLikePost(post._id, like._id)"> </ion-icon>
    <ion-icon name="heart-empty" class="icons" *ngIf="!like.likedBy._id == userId" (click)="addLike(post._id)"></ion-icon>
</span>

the problem with this is if there are n number of post.likes it will iterate for number of times and also the else statement is printed n number of times.

I am unable to perform *ngIf=(post.likes(x => x.likedBy._id == matchId))

what is the possible solution for this problem.

Pankaj Prakash
  • 2,300
  • 30
  • 31
Pratik Solanki
  • 75
  • 1
  • 2
  • 10
  • 1
    To filter on an ngFor loop you need to use a pipe in Angular 2+. Here is a good explanation: https://stackoverflow.com/a/34165371/1772933 – Kinglish May 05 '21 at 16:15

2 Answers2

0

you forgot to use find function for searching. but it is ALWAYS a bad idea to implement sorting, filtering,... operations on arrays directly in DOM. because it will cause jumps in your view when you deploy it on server.

you can use a get function as below:

html:

<span *ngFor="getPost">
   some elements
</span>

ts:

public get getPost() {
    return post.likes.find(x => x.likedBy._id == matchId);
}
Mahdi Zarei
  • 5,644
  • 7
  • 24
  • 54
0

Why don't you write a pipe for it.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'likes'
})
export class LikesPipe implements PipeTransform {

  transform(posts: any, userId: string): any[] {
    return posts.likes(x => x.likedBy._id == userId);
  }

}
<span *ngFor="let like of post | likes">
    <ion-icon name="heart" class="icons-heart" *ngIf="like.likedBy._id == userId; else elsehae" (click)="unLikePost(post._id, like._id)"> </ion-icon>
    <ion-icon name="heart-empty" class="icons" *ngIf="!like.likedBy._id == userId" (click)="addLike(post._id)"></ion-icon>
</span>

Note: Never ever wrap the pipe transform method logic directly in a component. As it impacts performance terribly. Always use pipes whenever you want to do data transformation.

Pankaj Prakash
  • 2,300
  • 30
  • 31