Angular中如何利用List组件高效展示数据列表?
在Angular中高效展示数据列表的核心方案:
使用*ngFor
时必加trackBy
// 组件中定义track函数
trackById(index: item, item: any): number {
return item.id; // 根据数据唯一标识跟踪
}
// 模板
<mat-list>
<mat-list-item *ngFor="let item of items; trackBy: trackById">
{{ item.name }}
</mat-list-item>
</mat-list>
虚拟滚动(处理大数据量)
// 安装Material CDK后
import { ScrollingModule } from '@angular/cdk/scrolling';
// 模板
<cdk-virtual-scroll-viewport itemSize="50" class="list-container">
<mat-list-item *cdkVirtualFor="let item of items">
{{ item.name }}
</mat-list-item>
</cdk-virtual-scroll-viewport>
分页懒加载(配合后端API)
// 使用MatPaginator
@ViewChild(MatPaginator) paginator: MatPaginator;
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.paginator.page
.pipe(
switchMap(() => this.loadPageData())
).subscribe();
}
OnPush
变更检测策略ng-container
减少DOM层级样式优化
.mat-list-item {
contain: strict; // 启用containment优化
will-change: transform; // 提示浏览器优化
}
选择策略依据:
*ngFor
+ trackBy
扩展方案:
@angular-component/router-store
管理列表状态注意:对于超大数据集(10万+),建议采用分窗算法(Windowed Rendering)并配合WebSocket实时更新。
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
npm install @angular/cdk rxjs
import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
private mockData = Array.from({ length: 1000 }, (_, i) => ({
}));
getData() {
}
}
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-list-demo',
templateUrl: './list-demo.component.html',
styleUrls: ['./list-demo.component.css']
})
export class ListDemoComponent implements OnInit {
items$ = this.dataService.getData();
constructor(private dataService: DataService) {}
// Track By 函数优化渲染
trackByFn(index: number, item: any) {
}
onClickItem(item: any) {
}
}
组件模板 (list-demo.component.html)
<!-- 虚拟滚动容器 -->
<cdk-virtual-scroll-viewport
class="scroll-area"
itemSize="56" <!-- 每个条目的高度 -->
style="height: 600px;"
<style>
.scroll-area {
}
.list-item {
}
.list-item:hover {
}
</style>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling'; // 导入虚拟滚动模块
import { AppComponent } from './app.component';
import { ListDemoComponent } from './list-demo.component';
@NgModule({
declarations: [
],
imports: [
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [CdkVirtualScrollViewport] // 注册虚拟滚动组件
})
export class AppModule { }