Angular 2: dynamically create divs

I want to create divs on the fly (using bootstrap classes) in angular 2 based on the value I get from the database. For example, I get 6 categories from db, so this will be displayed on screen in 3 div.row with 2 div.col-md-6 inside. How can I write a for loop in angular for this?

edit: or ask about it differently, how can I use ngFor to create elements only at odd indices?

+5
source share
1 answer

To fully answer your question, you need to see the structure of your object / array.

In any case, here's how you could check if this is strange:

<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 it is easy to do:

 @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 the channel:

live demo: https://plnkr.co/edit/8P15VdkWS4Oy02Ezevpp?p=preview

+1
source

Source: https://habr.com/ru/post/1264517/


All Articles