[Angular 2] *ngFor

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;
    }
}

here we can also use:

trackBy: hero?.id

heroes.component.css:

.even{
    background: lightgray;
}

.first{
    font-weight: bold;
}

.last{
    color: white;
    background: black;
}

原文地址:https://www.cnblogs.com/Answer1215/p/5872646.html