原文出处:https://www.cnblogs.com/Answer1215/p/5872646.html
heros.ts:
import {Component} from "@angular/core";
const HEROES = [
{id: 1, name:'Superman'},
{id: 2, name:'Batman'},
{id: 5, name:'BatGirl'},
{id: 3, name:'Robin'},
{id: 4, name:'Flash'}
];
@Component({
selector:'heroes',
styleUrls: [
'heroes.component.css'
],
template: `
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes; let i = index; trackBy: trackBy(hero);
let isEven=even; let isFirst=first; let isLast=last;"
[ngClass]="{'even': isEven, 'first': isFirst, 'last': isLast}">
<td>{{hero.name}}</td>
<td>{{i}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
heroes = HEROES;
trackBy(hero){
return hero ? hero.id: undefined;
}
}
注意: 上面的trackBy(hero)方法,似乎参数有问题,永远返回的都是: undefined; 最后参考这篇《Angular利用trackBy提升性能的方法》,“trackBy函数需要两个参数,第一个是当前项的index,第二个是当前项,并返回一个唯一的标识”。 将trackBy(hero) 改为: trackByID(index, item) html直接写 trackByID, 搞掂!
here we can also use:
trackBy: hero?.id
heroes.component.css:
.even{
background: lightgray;
}
.first{
font-weight: bold;
}
.last{
color: white;
background: black;
}