【发布时间】:2017-05-08 19:28:18
【问题描述】:
我正在使用 Angular2 *ngFor 并且对它何时重新创建 DOM 有点困惑。
如果我在 onClick() 中只有 case 1 代码,那么它将重新创建两个 <li>,但我只是将相同的值分配给 this.objArr。
如果我在 onClick() 中只有 case 2 代码,那么它不会重新创建两个 <li>,而只需再添加一个 <li>。我想知道 ngFor 如何确定何时重新创建 DOM。
我想做的是:
如果我只是将更多对象推送到现有数组中,除了为推送对象添加 DOM 之外,我如何让它为我重新创建现有 DOM?和案例 2 一样,我希望 ngFor 可以为我重新创建前两个 <li>。
HTML:
<button (click)="onClick($event)"></button>
<li *ngFor="let obj of objArr"></div>
.ts 文件:
constructor() {
this.objArr = [
{
'id': 0,
'content': 'test0'
},
{
'id': 1,
'content': 'test1'
}
];
}
onClick() {
// case 1: recreate two <li>
this.objArr = [
{
'id': 0,
'content': 'test0'
},
{
'id': 1,
'content': 'test1'
}
];
// case 2: just add one <li> after the two existing <li>
this.objArr.push({
'id': '2',
'content': 'test2'
});
}
【问题讨论】:
-
你可以使用管道
-
@VinayPandya 你能根据我的例子解释更多细节吗?