【问题标题】:Looping over array of objects to populate carousels in array of cards in angular循环遍历对象数组以以角度填充卡片数组中的轮播
【发布时间】:2020-10-05 17:31:45
【问题描述】:

我有一个由对象(id、image)组成的对象数组,并且我还有几张卡片作为我提取到后端的结果。 我想做的是在每张卡片上建立一个轮播,专门使用与卡片实际上具有的 id 匹配的图像,假设这是我的图像数组

arrayOfImages:[
 {id: "1",image: "xxxxxxxxxx"},
 {id: "1",image: "xxxxxxxxxx"},
 {id: "2",image: "xxxxxxxxxx"},
 {id: "2",image: "xxxxxxxxxx"},
 {id: "1",image: "xxxxxxxxxx"},
 {id: "2",image: "xxxxxxxxxx"}
]

让我们说在我的 html 标签上,我触发了 html:

<div  *ngFor="let post of allPortafolio;let i=index">
  //NgFor that bring me all cards from back
  //some code
  <ngb-carousel>
    //carousel specific for one card where in i want to loop over the array of images
    <ng-template ngbSlide *ngFor="let image of arrayOfImages">
      <img *ngIf="post.id===image.id;else alternative" [src]="image.image">
      <ng-template #alternative>
        <img " else  src="../../../assets/white.jpg">
      </ng-template>
    </ng-template>
  </ngb-carousel>
</div>

如您所见,必须使用 else ,使用其他固定模板,而循环保持其过程与 id 条件不匹配,但美观是可怕的,因为似乎页面在不断获取充电,而不是在旋转木马中顺畅流动。

但我想知道是否有另一种选择,我可以在不使用 else 的情况下循环该对象数组,并将其各自的图像分配给每张卡片,实际上卡片的 id 匹配,因此它们各自的轮播将流畅无间断

【问题讨论】:

    标签: arrays angular for-loop carousel


    【解决方案1】:

    实现您想要的更好的方法是在您的打字稿文件中创建一个函数,您可以在其中将帖子的 id 与 id 图像匹配并返回匹配的图像或通用图像。

    matchImage(post, image) {
      if (post.id === image.id) {
        return image.image
      } else {
        return '../../../assets/white.jpg'
      }
    }
    

    在您的 html 文件中:

    <div  *ngFor="let post of allPortafolio;let i=index">
      //NgFor that bring me all cards from back
      //some code
      <ngb-carousel>
        //carousel specific for one card where in i want to loop over the array of images
        <ng-template ngbSlide *ngFor="let image of arrayOfImages">
          <img [src]="matchImage(post, image)">
        </ng-template>
      </ngb-carousel>
    </div>
    

    如果您想要一个 stackblitz 演示,只需为您的问题制作一个可重现的小型演示,我很乐意使用此解决方案对其进行修改。

    【讨论】:

    • 保持相同的行为,但在这种情况下,因为它没有替代模板,只是当图像不匹配时卡片会变形
    • 检查你的默认图片,也许问题来自它
    • 问题是我不想在循环进行时有默认图像,这就是它目前的工作方式....我的想法是默认删除该图像并简单地分配给每张卡实际上,它的一组正确的图像与图像的 id 相协调
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多