是的,只在浏览器上进行虚拟滚动渲染时,我们可以使用
isPlatformBrowser
并解决它!
import { ChangeDetectionStrategy, Component, Inject } from '@angular/core';
import { NgIf } from '@angular/common';
import {ScrollingModule} from '@angular/cdk/scrolling';
@Component({
selector: 'app-root',
styleUrl: './app.component.scss',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
imports: [ScrollingModule, NgIf]
})
export class AppComponent {
items = Array.from({length: 100000}).map((_, i) => `Item #${i}`);
isBrowser: boolean;
constructor( @Inject(PLATFORM_ID) platformId: Object) {
this.isBrowser = isPlatformBrowser(platformId);
}
}
HTML
<ng-container *ngIf="isBrowser">
<div class="example-header">Content before</div>
<cdk-virtual-scroll-viewport scrollWindow itemSize="50">
<div *cdkVirtualFor="let item of items" class="example-item">{{item}}</div>
</cdk-virtual-scroll-viewport>
<div class="example-footer">Content after</div>
</ng-container>
顺便说一句,该组件使用
window
或
document
对象,因此在服务器上渲染毫无意义,这是一个仅限浏览器的功能,因为使用了
窗
或
文件
!