Reputation: 143
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>
Upvotes: 10
Views: 9934
Reputation: 2379
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 */
}
Upvotes: 22
Reputation: 66
You could use bootstrap CSS with html elements like
<section>
<div class="row bg-light" *ngFor="let row of Rows">
<div class="col-md-3 border cursor-action">
<label>
<b>{{row.label}}</b>
</label>
</div>
<div class="col-md-3 border cursor-action">
<input type="checkbox">
</div>
</div>
</section>
Hope this helps you
Upvotes: 0
Reputation: 92
There is only one CLEAN way to approach any layout which is the flexbox layout.
I tried and loved both of those solutions
2- Bootstrap Grid system https://getbootstrap.com/docs/4.0/layout/grid/
that's not a short answer but if u adopt any of them you will never ever have to struggle with layout again.
Cheers!
<div class="container-fluid">
<div class="row"
*ngFor="let row of rows;let i = index;">
<div class="d-flex align-items-center justify-content-xxxx">
<label for="cb{{i}}">some label</label>
<input id="cb{{i}}"
type="checkbox">
</div>
</div>
</div>
Upvotes: -2