Search code examples
htmlcssangularngfor

using *ngFor with grid CSS effectively


I would like to generate a grid based on unknown rows. The grid is simple with only two columns. One column containing row labels and the other some UI element such as a checkbox.

The only way I've been able to make this work is by generating a new grid with each loop through (see example below). I would like to accomplish this with a single ngFor and a single Grid.

Clarification, each label must be on the same row as their respective checkbox.

example :

    <div *ngFor="let row of rows">
      <div class="popup-grid">
        <div>
          {{row.label}}
        </div>
        <div>
          <p-checkbox  "angular interactions/events here">
          </p-checkbox>
        </div>
      </div>
   </div>

Solution

  • This is how you would use ngFor with CSS grid effectively. You can use ng-container to prevent *ngFor from inserting divs into the dom. This will prevent generating a new grid with each loop through.

    The Angular ng-container is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

    Then surround ng-container with a div with display: grid;. You can then use the grid-template-columns rule in order to define the amount of columns you want. Grid will automatically place rows. Check the example code below.

    HTML:

    <div class="grid">
        <ng-container *ngFor="let row of data">
            <label>{{row}}</label>
            <div><input type="checkbox"></div>
        </ng-container>
    </div>
    

    CSS:

    .grid {
        display: grid;
        grid-template-columns: 1fr 1fr; /* Create 2 columns and auto-place rows */
    }