I am still rather new to angular and I just could not find an example for the following issue:
Assume you have a components which displays just a list of items. Each item gets passed from the parent ItemsComponent to a child ItemComponent component. Classic example.
However, let's also assume that we wish to update the list of items whenever there is a change. So we do a nasty poll each 5 seconds (suggestions for better solutions are welcome). This will update items and destroy each ItemComponent child for new ones to be created.
@Component({
selector: 'app-items',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css'],
template:`
<div *ngFor="let item of items">
<app-item [item]="item"></app-item>
<div>
`
})
export class ItemsComponent implements OnInit {
private polling;
public items: Array<ItemModel>;
constructor(private itemsService: ItemsService) {}
ngOnInit() {
this.polling = interval(5000).pipe(
startWith(0),
map(() => {
this.itemsService.getItems().subscribe(
(items) => {this.items = items;});
})
).subscribe((data) => this.processData(data));
}
}
ngOnDestroy() {
this.polling.unsubscribe();
}
}
Now there are a few problems:
- The user will be scrolled back (rather snapped back) up to the top
- Any complex state e.g. a child being in fullscreen mode is lost too
All this would have to be remembered and dealt with in the parent component.
So is there an "angular" war to do this or do I have to implement the update logic myself in the parent component?
My biggest headache is the *ngFor directive. I know I can get a reference to those children using @ViewChildren but I could not manage to achieve what I am seeking here.
So how can we update items in a list view with angular?