首页 > 解决方案 > 访问 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>

标签: angular

解决方案


假设您有一个组件 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;

推荐阅读