The project encountered such a requirement: one of the fields in the queried data is an array of pictures, but when the previous detail page is displayed, the following layout is required:
Each line displays up to 3 pictures, so each line is traversed output, and each cell is also traversed output, but the data picture field is a simple array list, and there is no way to wrap every three elements; so in the end, only Can change the data structure in the array, that is, transform a one-dimensional array into a two-dimensional array:
One-dimensional array: [a, b, c, d, e, f, g, .....]
Two-dimensional array: [[a, b, c], [d, e, f], [g, h, i] ....]
If it is traversed like this, it will be fine;
I use angular6 for the front end, which is very convenient to traverse;
First, there are three variables in the code;
mydiary: any;
size = 3;
imgs: any[] = [];
The momentAttachmentList field in the mydiary object is an array of pictures;
size: the number displayed in each line; if 3 is not enough, you can set more;
imgs: new array to store pictures
Approach:
// 格式化图片成九宫格
formartImgs(): void {
if (this.mydiary.momentAttachmentList && this.mydiary.momentAttachmentList.length > 0) {
for (let index = 0; index < this.mydiary.momentAttachmentList.length; index += this.size) {
const element = this.mydiary.momentAttachmentList[index];
this.imgs.push(this.mydiary.momentAttachmentList.slice(index, index + this.size));
}
}
}
The previous page traversal code:
<ion-grid>
<ion-row *ngFor="let imgsRow of imgs">
<ion-col col-4 col-sm *ngFor="let img of imgsRow">
<img [src]="img.thumbnailPhoto">
</ion-col>
</ion-row>
</ion-grid>