I want to create divs on the fly (with bootstrap classes) in angular 2 based on a value I receive from the database. For example, I get 6 categories from the db, so that would translate on screen into 3 div.row having 2 div.col-md-6 inside. How can I write a for loop in Angular to do this?
edit: or to ask this otherwise, how can I use ngFor to create elements only on odd indices?
In order to fully answer your question it is necessary to see your object/array structure.
Anyway, here's how you would check if its odd:
<div *ngFor="let x of anyArray; let even = even; let odd = odd">
<div *ngIf="odd">odd</div>
<div *ngIf="even">even</div>
</div>
UPDATE
with your given structure its easy todo:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div *ngFor="let row of data" class="any class you want here">
<div *ngFor="let item of row" class="any class you want">
{{ item.id + ': ' + item.name }}
</div>
<br /> <!-- just to demonstrate a visual effect here! :) -->
</div>
</div>
`,
})
export class App {
name:string;
data = [
[{id:1,name:'name1'},{id:2,name:'name2'}],
[{id:3,name:'name3'},{id:4,name:'name4'}],
[{id:5,name:'name5'},{id:6,name:'name6'}]
];
constructor() {
this.name = 'Angular2'
}
}
live demo: https://plnkr.co/edit/XjS25h19Rjny4N6OVhN1?p=preview
Or using your first data approach and using a pipe:
live demo: https://plnkr.co/edit/8P15VdkWS4Oy02Ezevpp?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With