search

Home  >  Q&A  >  body text

Angular: Display data by rows (3 rows only)

I am new to programming.

I want to try using angular to display elements by rows, with a limit of 3 elements per row. (Use *ngFor)

For example, like this picture 3 elements by row

I used the slice pipeline, but this only requires the 3rd element.

<ul>
  <li *ngFor="let item of items | slice:0:3">
   {{ item }}
  </li>
</ul>

Can anyone help me or show me a code example

P粉322918729P粉322918729315 days ago404

reply all(1)I'll reply

  • P粉670838735

    P粉6708387352024-02-18 10:51:13

    You can use a simple *ngFor and use CSS Grid with any row or column to sort the elements. Alternatively, you can add grid-auto-flow: column; to sort the elements in the column.

    import {
      Component
    } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
      public arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8];
    }
    
    * {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    }
    
    .container {
      width: 100%;
      padding: 5px;
      box-sizing: border-box;
      display: grid;
      gap: 10px;
      grid-template-rows: repeat(3, auto);
      grid-template-columns: repeat(3, 1fr);
      grid-auto-flow: column;
    }
    
    .element {
      border: 2px solid black;
      text-align: center;
      font-weight: bold;
      padding: 5px;
      font-size: 12px;
    }
    
    Element {{ element }}

    You can try this code on stackblitz

    reply
    0
  • Cancelreply