我在UI中使用* ngFor绑定元素。该元素包含自定义复选框,该复选框根据数据示例中的条件检查值,item.isSelected = true。如果我单击复选框,我只将选定的复选框数据更改为修改器数组中的“item.isSelected = true”。如果我在数组中更改任何内容它也将自动反映在UI中。因为数据绑定到ng为它再次尝试将数据重新绑定到UI。但它需要很长时间的绑定值并检查UI中的复选框(仅在边缘浏览器中,其他像chrome,firefox做得好)。请给我一些建议来解决这个问题。
数据示例
[
{
body: "laudantium enim quasi est quidem magnam voluptate ipsam eos↵tempora
quo necessitatibus↵dolor quam autem quasi↵reiciendis "
email: "[email protected]"
id: 1
isSelected: false
name: "id labore ex et quam laborum"
postId: 1
}
.
.
.
upto 2500 objects
]
home.ts
export class HomePage {
commentArray: any = [];
constructor(public navCtrl: NavController, private http: Http) {
debugger
this.getdata();
}
getdata() {
//getting the data from API here
this.http.get('https://jsonplaceholder.typicode.com/comments').
subscribe(data => {
this.commentArray = JSON.parse(data['_body']);
//pass this to set data to set isSelected flag
this.setData(this.commentArray);
}, error => {
console.log(error);
})
}
setData(data) {
//here setting the isSelected flag
for (let i = 0; i < data.length; i++) {
data[i]['isSelected'] = false;
}
//getting only 500 data so copy the old data and push to array
for (let i = 0; i < 2000; i++) {
let d = data[0];
d.isSelected = false;
data.push(d);
}
this.commentArray = data;
//Total data now 2500
}
changeCheckbox(index){
debugger
console.time("Performance");
for(let i=0;i<this.commentArray.length;i++){
if(index == i){
this.commentArray[i].isSelected = true;
}else{
this.commentArray[i].isSelected = false;
}
}
console.timeEnd("Performance");
}
}
home.html的
<div>
<ul *ngFor="let item of commentArray;let i = index;">
<li (click)="changeCheckbox(i)">
<span>{{i}}</span>
<input type="radio" [checked]="item.isSelected" >
<span>{{item.name}}</span>
</li>
</ul>
</div>
鉴于您在Microsoft Edge中遇到问题(我没有优势),我只能猜测一些性能优化:
export class HomePage {
commentArray: any = [];
selectedComment: number | null = null;
constructor(public navCtrl: NavController, private http: Http) {
this.getdata();
}
getdata() {
this.http.get('https://jsonplaceholder.typicode.com/comments').
subscribe(data => {
// Only getting the first 500 items
this.commentArray = JSON.parse(data['_body']).slice(0,500);
}, error => {
console.log(error);
})
}
selectComment(index: number) {
this.selectedComment = index;
}
}
<div>
<ul *ngFor="let item of commentArray;let i = index;">
<li (click)="selectComment(i)">
<span>{{i}}</span>
<input type="radio" [checked]="selectedCheckbox === index" >
<span>{{item.name}}</span>
</li>
</ul>
最大的性能改进可能来自将组件的变化检测切换到ChangeDetectionStrategy.OnPush
。在视口中有这么多项目,它可能只是一个变化检测问题。
您还可以使用angular cdk VirtualForOf组件来减少浏览器需要同时呈现的项目数。