Angular 如何仅更新列表的一部分?
背景:Angular 如何仅更新列表的一部分?,angular,Angular,背景: 列表中的对象 列表被另一个具有相同项加/减对象的列表替换 问题:即使输入相同,列表中的每一项都会被销毁并重新创建 列表被另一个列表替换的原因是,它后面有一个可观察对象(angularfire2)。如何避免重新加载整个列表?是否有一种方法可以为列表中的每个项目创建单独的可观察项,并让这些项目监听更改 不确定这是否应该用angularfire2标记,因为我可以在angular2中创建相同的问题。在评论中留下一些有角度的评论 Plnkr: 从'@angular/core'导入{Compon
- 列表中的对象
- 列表被另一个具有相同项加/减对象的列表替换
从'@angular/core'导入{Component,Input};
//从“angularfire2”导入{AngularFire,FirebaseListObservable};
从'rxjs/BehaviorSubject'导入{BehaviorSubject};
@组成部分({
选择器:“我的应用程序”,
模板:''
})
导出类AppComponent{
公共项目=新的行为主体([{bah:1},{bah:2},{bah:3}]);
//公共项目:FirebaseListObservable;
构造函数(){//af:AngularFire){
设置超时(()=>{
接下来([{bah:1},{bah:2},{bah:3},{bah:4}]);
},3000);
/*this.items=af.database.list('/items');
本.项目.推送(1);
设置超时(()=>{
此。项目。推送(2);
},3000);*/
}
}
@组成部分({
选择器:“测试”,
模板:“{JSON.stringify(选项)}”
})
导出类TestComponent{
公共JSON=JSON;
@输入()选项;
ngOnChanges(更改){console.log('ngOnChanges');}
ngOnDestroy(){console.log('ngOnDestroy');}
ngOnInit(){console.log('ngOnInit');}
}
您可以使用trackBy
:
template: '<p *ngFor="let item of items | async; trackBy: itemToIndex" class="my-animation"><test [options]="item"></test></p>'
你试过使用trackBy吗?没有,我错过了,但似乎没有解决问题。Plnkr:当你说“重新加载”时,你指的是变量还是视觉元素?我只关心对Ngondestory的调用。我不想因为有人将某个项推到列表中而重新加载每个项。我不得不使用函数,这让我内心很难过就这样:P谢谢你!
template: '<p *ngFor="let item of items | async; trackBy: itemToIndex" class="my-animation"><test [options]="item"></test></p>'
itemToIndex(item: any){
return item.index;
}