在使用Angular Material中的虚拟滚动功能时,当其中的内容数量发生变化时,高度可能无法正确地调整。解决方法是使用ViewChild来访问滚动条,然后在内容发生变化时手动调整高度。下面是一个示例代码:
HTML模板文件:
{{ item }}
组件类文件:
import { Component, ElementRef, ViewChild } from '@angular/core';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
@ViewChild('scrollViewport') scrollViewport: CdkVirtualScrollViewport;
items: string[] = [];
addItem() {
this.items.push('new item');
this.scrollViewport.checkViewportSize();
}
onScroll() {
// do something
}
}
在这个示例中,我们使用ViewChild来引用滚动条,然后在addItem方法中添加新项并手动调用checkViewportSize方法来调整高度。