在 angular 中使用 ngIf 在嵌套对象数组中查找数据
finding data inside nested array of object with ngIf in angular
如何在嵌套数据循环中执行搜索
<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._id == matchId))
这个问题的可能解决方案是什么。
您忘记使用查找功能进行搜索。但是在 DOM 中直接对数组进行排序、过滤等操作总是一个坏主意。
因为当你在服务器上部署它时,它会导致你的视图跳转。
您可以使用如下获取函数:
html:
<span *ngFor="getPost">
some elements
</span>
ts:
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);
}
}
<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>
注意:永远不要将管道转换方法逻辑直接包装在组件中。因为它会严重影响性能。每当您想进行数据转换时,请始终使用管道。
如何在嵌套数据循环中执行搜索
<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._id == matchId))
这个问题的可能解决方案是什么。
您忘记使用查找功能进行搜索。但是在 DOM 中直接对数组进行排序、过滤等操作总是一个坏主意。 因为当你在服务器上部署它时,它会导致你的视图跳转。
您可以使用如下获取函数:
html:
<span *ngFor="getPost">
some elements
</span>
ts:
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);
}
}
<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>
注意:永远不要将管道转换方法逻辑直接包装在组件中。因为它会严重影响性能。每当您想进行数据转换时,请始终使用管道。