Angular中ngFor控制每行图片数量,实现每10张自动换行
Absolutely, you can pull this off easily by splitting your pics array into groups of 10 first, then using nested *ngFor loops to render rows and their corresponding cells. Here's a step-by-step breakdown:
Step 1: Add a Helper Property in Your Component
In your component class, create a getter that splits the pics array into rows of 10 images each. This simplifies looping over rows in your template:
import { Component } from '@angular/core'; @Component({ // Your existing component metadata (selector, templateUrl, etc.) }) export class YourComponent { pics = []; // Your existing array of image objects picroute = ''; // Your existing base image route // Getter to split pics into rows of 10 get picRows() { const chunkSize = 10; const rows: any[][] = []; for (let i = 0; i < this.pics.length; i += chunkSize) { rows.push(this.pics.slice(i, i + chunkSize)); } return rows; } // Your existing addpic method addpic(isChecked: boolean, id: any) { // Keep your existing logic here } }
Step 2: Update Your Template to Render Rows and Cells
Modify your template to use two nested *ngFor loops: the outer loop creates a new <tr> for each row of 10 images, and the inner loop generates <td> elements for each image in the row. I also fixed a couple of minor issues in your original code (like the unclosed img tag) and switched to Angular's property binding for better practice:
<table> <!-- Outer loop: creates a new table row for every 10 images --> <tr *ngFor="let row of picRows"> <!-- Inner loop: creates a table cell for each image in the row --> <td *ngFor="let item of row"> <div class="checkbox"> <label> <input type="checkbox" [checked]="item.checked" [value]="item.url" (change)="addpic($event.target.checked, item.id)" > </label> </div> <img [src]="picroute + item.img" alt="Gallery image"> </td> </tr> </table>
Alternative: CSS-Based Wrapping (If You Don't Need Explicit Table Rows)
If you don’t strictly require HTML table rows and just want images to wrap after 10 items, you could use CSS Grid or Flexbox instead. This skips the array chunking logic entirely:
CSS (Grid Example)
.image-grid { display: grid; grid-template-columns: repeat(10, 1fr); gap: 1rem; }
Simplified Template
<div class="image-grid"> <div *ngFor="let item of pics"> <div class="checkbox"> <label> <input type="checkbox" [checked]="item.checked" [value]="item.url" (change)="addpic($event.target.checked, item.id)" > </label> </div> <img [src]="picroute + item.img" alt="Gallery image"> </div> </div>
But since you specifically asked about using ngFor to create new rows, the first method (array chunking + nested loops) is the perfect match for your needs.
内容的提问来源于stack exchange,提问作者Mark

