angular - 访问 ngFor 循环中的元素
问题描述
我想在遍历图像对象数组的 ngFor 循环中访问当前图像 url(url 是图像对象的属性)。我想在相同的组件打字稿文件中访问它。
我虽然也许我可以使用 @Input() 绑定到相同组件 .ts 文件中的属性,但我相信这是针对子/父关系的。
我将如何以角度进行此操作?
相关html:
<div
class="image-container"
*ngFor="let image of galleryList"
[imageUrl]="image.Url">
</div
相关ts代码:
@Input() imageUrl: string;
我不希望上面的代码能够工作,但我只是想向您展示我想要实现的目标。
最终,我试图在打字稿文件中使用此方法中的图像 url:
checkLike(imageUrl: string): boolean {
const users = this.usersService.getUsers();
if(this.isLoggedIn) {
const currUsersIndex = this.usersService.getCurrUserArrIndex();
console.log(currUsersIndex);
const FavouritesList = users[currUsersIndex].likes;
if(FavouritesList.includes(imageUrl)) {
return true;
} else {
return false;
}
}
}
然后根据结果有条件地添加html元素:
<div *ngIf="checkLike(image.imagePath)" class="heart-icon-container">
<ion-icon name="heart" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
</div>
<div *ngIf="!checkLike(image.imagePath)" class="heart-icon-container">
<ion-icon name="heart-outline" class="heart-icon" (click)="updateLike(image.imagePath)"></ion-icon>
</div>
解决方案
假设您有一个组件 abc-component,您可以像这样使用它
<abc-component *ngFor="let image of galleryList" [imageUrl]="image.Url"></abc-component>
但是您不能将输入传递给普通 div,除非您将组件的选择器更改为属性,例如:-
@Component({
selector: [abc-component],
....
})
然后你可以像这样使用它:-
<div *ngFor="let image of galleryList" [imageUrl]="image.Url" abc-component></div>
并将其放在 Abc 组件中,例如
@Input() imageUrl: string;
推荐阅读
- php - 是否可以覆盖 back() 函数中的参数
- android - 如何修复 RecyclerView 正在计算布局或滚动时无法调用此方法
- macos - 实体文件已更改为符号链接
- android - Android,mapFragment.getMapAsync 错误发生空对象引用
- python - Python Selenium 库中的“str”对象不可调用
- javascript - 为什么要删除悬停状态行为?
- amazon-web-services - 如何自动定期重建 AWS Elastic BeanStalk 环境?
- scala - 如何在模拟中通过 Scala 类
- javascript - 在 ionic 中使用动态值翻译 innerhtml
- python - 二维点数据的等高线图