[英]Add Item after NTH element with ion-item
我想在每 8 個項目后添加一個圖像。 該圖像將是 ion-item 元素中唯一的項目。 此圖像不是 items 數組的一部分,而是來自另一個數組。
我正在使用這個(簡化的)代碼:
<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
的索引和模運算符來實現這一點。 請看一下這個有效的 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}`
});
}
}
}
模板
<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
數組中的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.