Tim Burkhart Tim Burkhart - 2 months ago 56
TypeScript Question

Angular2 + Bootstrap Grid

In Angular2, I have a list of objects and I'm trying to use bootstrap's grid layout system, but am having some difficulty figuring out how to best do this in Angular2. Any help would be appreciated!

If I was using HandlebarsJS, I could accomplish this with the following code:

{{#for elements}}
{{#if index % 12 === 0}}
<div class="row">
{{/if}}
<div class="col-md-2">
{{element.name}}
</div>
{{#if index % 12 === 0}}
</div>
{{/if}}
{{/for}}


So I want it to look like:

<div class="row">
<div class="col-md-2">
Bob
</div>
<div class="col-md-2">
Joe
</div>
...
</div>
<div class="row">
<div class="col-md-2">
Julie
</div>
<div class="col-md-2">
Cheryl
</div>
...
</div>

Answer

This is the rehashing of an old debate, but for a new version of Angular. Some of the more popular/creative solutions for this question in Angular 1.x can be found here and can be updated for your purposes. Personally, I favor Duncan's solution, but I think that's a matter of opinion. An updated version of that code for Angular2 with a simple Codepen below:

  <div class="row">
    <div *ngFor="let hero of heroes; let i = index">
      <div class="clearfix" *ngIf="i % 3 == 0"></div>
      <div class="col-md-4">{{hero.name}}</div>
    </div>
  </div>

Working Codepen

Codepen Note: Blue background color is the row. Red is the col-md-* cell.

As you can see, this code only uses one row element that wraps all of the col-* elements and inserts a clearfix element every x elements. IMO, this solution is relatively clean and seems to employ more of a Google Material Design Lite (MDL)-style grid implementation for rows and cells than the Bootstrap standard row/col implementation.

Granted, none of these answers provide you with exactly what you asked for, but it's a bit of apples to oranges.

Comments