Angular ngAfterViewInit()中的呈现变量工作不正常
ngAfterViewInit()中的任何变量更改最近正在工作 这里是stackblitz应用程序 组件文件Angular ngAfterViewInit()中的呈现变量工作不正常,angular,angular-material,Angular,Angular Material,ngAfterViewInit()中的任何变量更改最近正在工作 这里是stackblitz应用程序 组件文件 从'@angular/core'导入{ChangeDetectionStrategy,ViewChild,AfterViewInit,Component,ChangeDetectorRef}; 从“@angular/cdk/scrolling”导入{CdkVirtualScrollViewport}; @组成部分({ 选择器:“cdk虚拟滚动概览示例”, 样式URL:['cdk-virt
从'@angular/core'导入{ChangeDetectionStrategy,ViewChild,AfterViewInit,Component,ChangeDetectorRef};
从“@angular/cdk/scrolling”导入{CdkVirtualScrollViewport};
@组成部分({
选择器:“cdk虚拟滚动概览示例”,
样式URL:['cdk-virtual-scroll-overview-example.css'],
templateUrl:'cdk虚拟滚动概览示例.html',
changeDetection:ChangeDetectionStrategy.OnPush,
})
导出类CDKVirtualScrolOverviewExample实现AfterViewInit{
指数:数字=1;
@ViewChild(CdkVirtualScrollViewport)视口:CdkVirtualScrollViewport;
items=Array.from({length:100000}).map({uu,i)=>`Item}${i}`);
构造函数(私有cdRef:ChangeDetectorRef){}
ngAfterViewInit():void{
this.viewPort.scrolledIndexChange.subscribe(索引=>{
控制台日志(索引);
这个指数=指数;
});
this.cdRef.detectChanges();
}
}
HTML文件
{{item}}
{{index}}
滚动虚拟选项卡时,索引值正在更改,这不是问题。
但是当比较console.log()和浏览器中的索引值时,这些值似乎是最近更新的,而不是当时更新的。我错过了什么
差异
我的目标是变量必须同步。如果控制台输出为1,则呈现的HTML索引值应为1。请帮我解决我遗漏的问题?您需要在订阅块中运行更改检测,以便在更改滚动时立即运行
ngAfterViewInit():void {
this.viewPort.scrolledIndexChange.subscribe(index => {
console.log(index);
this.index = index;
this.cdRef.detectChanges();
});
}
请使用此stackblitz实例-