Angular 14中*ngFor渲染下拉框导致页面卡顿问题求助
问题:Angular 14中使用
*ngFor生成下拉框导致页面卡顿崩溃 我在Angular 14里用*ngFor,基于LaptopComponent传递的数据在GenericLayoutComponent中创建下拉框,但页面出现卡顿甚至崩溃。已经尝试用trackBy优化*ngFor性能,但问题依旧。
相关代码
GenericLayoutComponent
HTML模板(generic-layout.component.html)
<div *ngFor="let i of data"> <p-dropdown [options]="i" [(ngModel)]="selectedValue" optionLabel="name" (onChange)="onChange()" ></p-dropdown> </div>
TypeScript代码(generic-layout.component.ts)
export class GenericLayoutComponent implements OnInit { @Input() product: string; @Input() data; selectedValue; constructor() {} ngOnInit() {} onChange() { console.log(this.selectedValue); } }
LaptopComponent(数据传递)
TypeScript代码(laptop.component.ts)
export class LaptopComponent implements OnInit { company = []; battery_hours = []; data = []; constructor() { this.company = [ { name: 'Samsung', code: 'SSM' }, { name: 'Apple', code: 'APL' }, { name: 'Micromax', code: 'MMx' }, ]; this.battery_hours = [ { name: '10 hours' }, { name: '25 hours' }, { name: '32 hours' }, ]; this.data = [this.company, this.battery_hours]; } ngOnInit() {} }
HTML模板(laptop.component.html)
<app-generic-layout [product]="'Laptops'" [data]="data"> </app-generic-layout>
问题原因及解决方案
核心问题
所有下拉框共享同一个selectedValue变量,当任意一个下拉框选中值时,会触发ngModel的变更检测,导致所有下拉框重新渲染,形成循环触发逻辑,最终引发页面卡顿崩溃。
修复步骤
为每个下拉框维护独立选中值
修改GenericLayoutComponent,将单个selectedValue改为数组,对应每个下拉框的选中状态:export class GenericLayoutComponent implements OnInit { @Input() product: string; @Input() data; selectedValues: any[] = []; constructor() {} ngOnInit() { // 初始化数组,长度与传入的data一致 this.selectedValues = new Array(this.data?.length).fill(null); } onChange(index: number, value: any) { this.selectedValues[index] = value; console.log('当前选中值:', this.selectedValues[index]); } }更新HTML模板绑定逻辑
绑定对应索引的选中值,并将索引传递到onChange方法:<div *ngFor="let i of data; let index = index; trackBy: trackByIndex"> <p-dropdown [options]="i" [(ngModel)]="selectedValues[index]" optionLabel="name" (onChange)="onChange(index, $event.value)" ></p-dropdown> </div>添加trackBy函数优化性能
在GenericLayoutComponent中添加trackBy函数,避免不必要的DOM重渲染:trackByIndex(index: number): number { return index; }
通过以上修改,每个下拉框拥有独立的选中状态,彻底避免了共享变量导致的循环变更检测,从根源解决页面卡顿崩溃问题。
内容的提问来源于stack exchange,提问作者Tanzeel
相关产品推荐
相关产品推荐

