我有一些列表,可以添加/删除列表中的项目.
例如,当我在列表的中间(或底部)时,如果我将项目添加到列表中,滚动将移动到列表的顶部.(或者移动到某个索引,本例中为索引0).
告诉我如何在不改变示例 struct 的情况下从父组件滚动到子组件.
我有一些列表,可以添加/删除列表中的项目.
例如,当我在列表的中间(或底部)时,如果我将项目添加到列表中,滚动将移动到列表的顶部.(或者移动到某个索引,本例中为索引0).
告诉我如何在不改变示例 struct 的情况下从父组件滚动到子组件.
您的问题是,ViewChild在查询时不会进入更深的层次,因此无法在子元素模板中查询CdkVirtualScrollViewport.我可以用custom change detection function in your list component解决这个问题.
您应该将其从app.ts -> addItem()函数中删除:
// want to move scroll to the top of the list
this.viewPort.scrollToIndex(0, 'smooth');
而是在list component中创建自定义更改检测功能,但首先将CdkVirtualScrollViewport的viewChild移动到list component:
export class ListComponent {
@ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;
@Input()
data: Favorite[];
@Output()
removeData = new EventEmitter<Favorite>();
remove($event) {
this.removeData.emit($event);
}
ngOnChanges(changes: SimpleChanges) {
if (
changes.data &&
changes.data.currentValue &&
changes.data.previousValue &&
changes.data.currentValue.length >changes.data.previousValue.length
) {
this.viewPort.scrollToIndex(0, 'smooth');
}
}
}
这对我来说非常有效.每次添加项目时,它都会滚动到顶部.
修改了stackblitz链接:
https://stackblitz.com/edit/angular-ivy-k5pve6?file=src/app/list/list.component.ts
Another solution(and maybe better)可以将ListComponent作为模板引用传递给addItem()函数,然后使用Components viewPort property的滚动函数.
列表组件
...
export class ListComponent {
@ViewChild(CdkVirtualScrollViewport)
public viewPort: CdkVirtualScrollViewport;
...
}
AppComponentTemplate,模板引用传递ListComponent:
<p>Start editing to see some magic happen :)</p>
<input #inputText />
<button #addButton (click)="addItem(list)">Add New</button>
<list-container #list [data]="favoriteList" (removeData)="remove($event)">
</list-container>
应用组件->;addItem():
addItem(listComp: ListComponent) {
const newItem = {
id: Number(this.input.nativeElement.value) + 1,
title: `item ${Number(this.input.nativeElement.value) + 1}`,
};
this.favoriteList = [newItem, ...this.favoriteList];
listComp.viewPort.scrollToIndex(0, 'smooth');
}
第二种解决方案的StackBlitz:
https://stackblitz.com/edit/angular-ivy-ofhubv?file=src/app/app.component.html