文章参考
- 官网
- 在Angular中利用trackBy来提升性能
- angular中ngFor的参数
属性介绍
- index: number:可迭代对象中当前条目的索引。
- first: boolean:如果当前条目是可迭代对象中的第一个条目则为 true。
- last: boolean:如果当前条目是可迭代对象中的最后一个条目则为 true。
- even: boolean:如果当前条目在可迭代对象中的索引号为偶数则为 true。
- odd: boolean:如果当前条目在可迭代对象中的索引号为奇数则为 true。
trackBy来提升性能
- 为 *ngFor添加一个trackBy函数,告诉Angular该怎么跟踪集合的各项。
- trackBy函数需要两个参数,第一个是当前项的index,第二个是当前项,并返回一个唯一的标识,就像这样:
案例
模板
<ul>
<li *ngFor="let friendName of userInfoObj.friends;let i=index;
let first=first;let last=last;odd as odd;even as even;
trackBy: friendsTrackByIndex
">
<span *ngIf="first">我是第一个---{{friendName}} ---- {{index}} ----- {{i}}</span>
<span *ngIf="odd">我是奇数行-----{{friendName}} ---- {{index}} ----- {{i}}</span>
<span *ngIf="even">我是偶数行---{{friendName}} ---- {{index}} ----- {{i}}</span>
<span *ngIf="last">我是最后一个----{{friendName}} ---- {{index}} ----- {{i}}</span>
</li>
</ul>
组件中定义数据
import { Component, OnInit } from '@angular/core';
interface Student {
name: string,
age?: number,
friends: any[],
[propName: string]: any;
}
@Component({
selector: 'app-basic-page',
templateUrl: './basic-page.component.html',
styleUrls: ['./basic-page.component.scss']
})
export class BasicPageComponent implements OnInit {
userInfoObj: Student;
imgUrl: string = 'http://n.sinaimg.cn/news/1_img/dfic/3ad618a7/128/w1024h704/20190924/364c-ifaencf3678695.jpg';
isShowAge: boolean = true;
constructor() {
this.userInfoObj = {
name: 'naoteng',
age: 18,
friends: ['qiqi', 'yuke', 'yiming', 'siyou', 'siyu', 'junkai', 'hongyang'],
isMarried: false
}
}
getUserInfo () {
alert(this.userInfoObj.name)
}
ngOnInit() {
}
friendsTrackByIndex (index, item) {
console.log(index, item);
return index
}
}