Javascript 使用ngIf在angular中查找对象嵌套数组中的数据
如何在嵌套的数据循环中执行搜索Javascript 使用ngIf在angular中查找对象嵌套数组中的数据,javascript,angular,ngfor,Javascript,Angular,Ngfor,如何在嵌套的数据循环中执行搜索 <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)"
<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>
问题是如果有n次post.likes
它将迭代多次,并且else语句被打印n次
我无法执行*ngIf=(post.likes(x=>x.likedBy.\u id==matchId))
此问题的可能解决方案是什么。您忘记使用“查找”功能进行搜索。但是,实现排序、过滤等总是一个坏主意,。。。直接在DOM中对数组执行操作。 因为当您将其部署到服务器上时,它会导致视图跳转 您可以使用下面的get函数: html:
你为什么不为它写一个烟斗呢
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);
}
}
注意:永远不要将管道转换方法逻辑直接包装到组件中。因为它严重影响性能。要进行数据转换时始终使用管道。要在ngFor循环上进行过滤,需要在Angular 2+中使用管道。这里有一个很好的解释:
public get getPost() {
return post.likes.find(x => x.likedBy._id == matchId);
}
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);
}
}