我们最近将可滚动列表转换为 CDK Virtual Scroller。 (Angular 7.2.12 和 Angular/cdk 7.3.7)
简而言之,似乎VirtualScrollViewport
正在回收组件实例,而不仅仅是文档建议的模板。
StackBlitz 上的实时 MCVE(更新以反映编辑 1)。
EDIT 1
一位同事提醒我,我们现在使用命名引用而不是ViewChildren()
,像这样:
HelloComponent
(在 - 的里面*cdkVirtualFor
):
@Component({
selector: 'hello',
template: `<h1 [class.active]="active">Data Item {{item}} !</h1>`,
styles: [`.active {background-color: red; color: white}`]
})
export class HelloComponent {
@Input() item: any;
active: boolean = false;
toggle = () => this.active = !this.active;
}
并在应用程序中实现它,例如:
<cdk-virtual-scroll-viewport itemSize="75">
<ng-container *cdkVirtualFor="let item of data" templateCacheSize=0>
<hello #hi [item]="item" (click)="clickByReference(hi)"></hello>
</ng-container>
</cdk-virtual-scroll-viewport>
// Non-essentials hidden, see StackBlitz
export class AppComponent {
data = Array.from(Array(100).keys())
clickByReference = (element: any): void => element.toggle();
}
它将把单击的元素的背景颜色更改为红色,但是当滚动时,其他元素(大概是那些与某些缓存索引匹配的元素?)已经是红色了!激活其中之一也会清除原始内容。
消息来源暗示 that templateCacheSize
可能有帮助,但没有帮助。
Original
可滚动区域包含我们通过@ViewChildren()
and QueryList
我们使用索引来跟踪我们正在对哪一个进行操作*ngFor
(now *cdkVirtualFor
),像这样:
<cdk-virtual-scroll-viewport itemSize="75">
<ng-container *cdkVirtualFor="let item of data; let i = index">
<hello #hi
[item]="item"
(click)="click(i)"></hello>
</ng-container>
</cdk-virtual-scroll-viewport>
然后,从页面中,我们与列表中的组件进行通信:
export class AppComponent {
@ViewChildren('hi') hiRefs: QueryList<HelloComponent>;
data = Array.from(Array(100).keys())
click = (i: number) => this.hiRefs["_results"][i].say(`Hello as ${i}`);
}
当然,现在模板是在虚拟滚动容器中渲染的,只有第一个n
被渲染到 DOM 中。因此,如果您向下滚动列表超出最初加载的内容,hiRefs
不包含对具有相应索引的项目的引用,抛出ReferenceError
对于提供的["_results"][i]
.
我尝试过trackBy
但没有取得任何成果。
EDIT:一位同事也尝试传递一个命名引用,奇怪的是它也有同样的问题。
更新中HelloComponent
to
@Component({
selector: 'hello',
template: `<h1 [class.active]="active">Data Item {{item}} !</h1>`,
styles: [`.active {background-color: red}`]
})
export class HelloComponent {
@Input() item: any;
active: boolean;
say = (something: any) => this.active = !this.active;
}
并在应用程序中实现它,例如:
<hello #hi [item]="item" (click)="clickByReference(hi)"></hello>
它将把单击的元素的背景颜色更改为红色,但是当滚动时,其他元素(大概是那些匹配相同索引的元素)将已经是红色的,尽管没有使用 @ViewChildren()
QueryList
at all!
看来CDK正在回收组件实例引用?
我用该方法更新了 StackBlitzclickByReference()
,并将上面的重命名为clickByIndex()
.
如何正确获取列表中组件的引用以便调用其方法?