Angular 2:动态创建div [英] Angular 2: create divs dynamically
问题描述
我想根据从数据库接收到的值,在角度2中随时创建div(使用引导类)。例如,我从数据库中获得6个类别,这样就可以在屏幕上转换成3个div.row,里面有2个div.col-md-6。如何在Angular中编写一个for循环来做到这一点?
编辑:或者询问这个问题,我怎样才能用ngFor创建奇数索引的元素?为了完全回答你的问题,有必要看看你的对象/数组结构。
无论如何,这里是你如何检查是否奇数:
$ b
< ; div * ngFor =let x of anyArray; let even = even; let odd = odd>
< div> ngIf =奇数>奇数< / div>
< div * ngIf =偶数>偶数< / div>
< / div>
更新 $ b $ b
@Component({
selector :'my-app',
模板:`
< div>
< h2> Hello {{name}}< / h2>
< ; div * ngFor =让数据行class =你想要的任何类>
< div * ngFor =让行的项目class =任何你想要的类>
{{item.id +':'+ item.name}}
< / div>
< br />效果在这里!:) - >
< / div>
< / div>
`,
})
export class App {
name:string;
数据= [
[{id:1,name:'name1'},{id:2,name:'name2'}],
[{id:3 ,name:'name3'},{id:4,name:'name4'}],
[{id:5,name:'name5'},{id:6,name:'name6'}]
];
构造函数(){
this.name ='Angular2'
}
}
现场演示: https://plnkr.co /编辑/ XjS25h19Rjny4N6OVhN1?p =预览
或使用您的第一个数据方法并使用管道:
现场演示: https://plnkr.co/edit/8P15VdkWS4Oy02Ezevpp?p=preview
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
这篇关于Angular 2:动态创建div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!