Angular 将元素添加到 NgRx 存储后滚动到视图

Angular scrollIntoView after adding an element to NgRx store

我有一个动态添加到我的视图并存储在 NgRx 中的项目列表:

<app-item *ngFor="let item of items$ | async"></app-item>

如果我单击 "Add item" 按钮,该项目将添加到 NgRx 商店。

我现在想在添加新项目时对项目引用调用 scrollIntoView。我尝试在项目的 ngOnInitngAfterViewInit 处调用 scrollIntoView,但它也会在页面加载时触发。我只想在将项目添加到列表并呈现时将其居中放置在页面中。

我怎样才能做到这一点?

我能想到的:

创建一个变量,表示items中新增的item索引

newestIndex; //the index of the newly added item inside items.

在您的 addItem() 函数中,更新索引。

addItem(item){
  // update item , update ngrx store and also update the newestIndex.   

}

使用 ViewChildren 装饰器获取所有组件项

@ViewChildren(AppItemComponent) appitems: QueryList<AppItemComponent>

现在,当项目更新时,您可以滚动到视图中。

items$.pipe(skip(1))     //skip first value as it is not caused by add item.
.subscribe( items =>{
    this.appitems[newestIndex].nativeElement.scrollIntoView();
})