I have a list of items that are added dynamically to my view and stored in NgRx:
<app-item *ngFor="let item of items$ | async"></app-item>
If I click on an "Add item" button the item is added to the NgRx store.
I now want to call scrollIntoView
on the item reference when a new item is added. I tried to call scrollIntoView
at ngOnInit
or ngAfterViewInit
of the item but it gets triggered also on page load. I only want to center the item in the page when it is added to the list AND it is rendered.
How can I achieve this?
What I can think of:
Create a variable indicating the newly added item index inside items
newestIndex; //the index of the newly added item inside items.
In your addItem() function, update the index.
addItem(item){
// update item , update ngrx store and also update the newestIndex.
}
Use a ViewChildren decorator to get all component items
@ViewChildren(AppItemComponent) appitems: QueryList<AppItemComponent>
And now when items update, you can scroll into view.
items$.pipe(skip(1)) //skip first value as it is not caused by add item.
.subscribe( items =>{
this.appitems[newestIndex].nativeElement.scrollIntoView();
})