使用 ion-item 在 NTH 元素后添加 Item

Add Item after NTH element with ion-item

我想在每 8 件商品后添加一张图片。该图像将是 ion-item 元素中的唯一项目。此图像不是项目数组的一部分,而是来自另一个数组。

我正在使用这个(简化的)代码:

<ion-list>
  <ion-item *ngFor="let item of items; let i = index" (click)="goTo()>
    <img src="{item.image}}">
    <h2>{{ item.name }}</h2>
  </ion-item>
</ion-list>

如何每 8 个项目插入一张图片?

您可以使用 ngFor 的索引和取模运算符来实现。请看一下this working StackBlitz project演示使用Ionic 3,但逻辑与Ionic 4完全相同)。

在下面的代码中,我刚刚创建了两个列表以在视图中显示一些项目:

组件

import { Component } from '@angular/core';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public items = [];
  public otherImages = [];

  constructor() {

    // Prepare some items
    for(let i = 1; i < 30; i++) {
      this.items.push({
        name: `Item ${i}`,
        image: `https://via.placeholder.com/160x160?text=Item+${i}`
      });
    }

    // Prepare some extra images
    for(let j = 1; j < 5; j++) {
      this.otherImages.push({
        image: `https://via.placeholder.com/160x160?text=Another+Image+${i}`
      });
    }
  }
}

模板

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>

  <ion-list>
    <ng-container *ngFor="let item of items; let i = index">

      <ng-container *ngIf="i > 0 && i % 8 === 0; else noImage">

        <!-- First show the image -->
        <ion-item *ngIf="i >= 8 && otherImages[i / 8 - 1]">
          <img [src]="otherImages[i / 8 - 1].image">
        </ion-item>

        <!-- Then show the item -->
        <ion-item>
          <img [src]="item.image">
          <h2>{{ item.name }} </h2>
        </ion-item>

      </ng-container>

      <ng-template #noImage>

        <!-- Only show the item -->
        <ion-item>
          <img [src]="item.image">
          <h2>{{ item.name }}</h2>
        </ion-item>

      </ng-template>

    </ng-container>
  </ion-list>

</ion-content>

在上面的代码中,第一个 *ngFor="let item of items; let i = index" 只是遍历 items 数组中的项目列表。

然后我们可以检查索引,看是否i > 0 && i % 8 === 0这意味着当前索引是数组的第8、16、24、...元素。

由于数组是从零开始的,因此索引 8 表示第 9 个元素。这意味着我们需要首先显示 额外图像 ,然后是 items 数组中的第 9 个元素。

请注意,为了从 otherImages 数组中获取正确的图像,我们需要让索引执行以下操作:otherImages[i / 8 - 1].image.

      <ng-container *ngIf="i > 0 && i % 8 === 0; else noImage">

        <!-- First show the image -->
        <ion-item *ngIf="i >= 8 && otherImages[i / 8 - 1]">
          <img [src]="otherImages[i / 8 - 1].image">
        </ion-item>

        <!-- Then show the item -->
        <ion-item>
          <img [src]="item.image">
          <h2>{{ item.name }} </h2>
        </ion-item>

      </ng-container>

如果索引不同,我们只需要显示项目:

      <ng-template #noImage>

        <!-- Only show the item -->
        <ion-item>
          <img [src]="item.image">
          <h2>{{ item.name }}</h2>
        </ion-item>

      </ng-template>