Вы можете использовать индекс ngFor
и оператор по модулю для достижения этого. Пожалуйста, посмотрите на этот работающий проект StackBlitz ( в демонстрационной версии используется 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}`
});
}
}
}
Template
<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-й элемент. Это означает, что нам нужно сначала показать дополнительное изображение , а затем 9-й элемент из массива items
.
Обратите внимание, что для получения правильного изображения из массива 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>