Skip to content

Instantly share code, notes, and snippets.

@angular-academy-devs
Last active February 22, 2023 03:22
Show Gist options
  • Save angular-academy-devs/8a4d3a1e420798e2cd534144b50ef180 to your computer and use it in GitHub Desktop.
Save angular-academy-devs/8a4d3a1e420798e2cd534144b50ef180 to your computer and use it in GitHub Desktop.
ngFor
<heroes>
<hero id="1" name="Superman"></hero>
<hero id="2" name="Batman"></hero>
<hero id="3" name="Batgirl"></hero>
<hero id="3" name="Robin"></hero>
<hero id="4" name="Flash"></hero>
<hero id="5" name="Green Lantern"></hero>
</heroes>
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes">
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
heroes = HEROES;
}
import {Component, ContentChildren, QueryList} from "@angular/core";
import {Hero} from "./hero";
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes;" >
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
@ContentChildren(Hero)
heroes: QueryList<Hero>;
}
const HEROES = [
{id: 1, name:'Superman'},
{id: 2, name:'Batman'},
{id: 5, name:'BatGirl'},
{id: 3, name:'Robin'},
{id: 4, name:'Flash'}
];
<tr *ngFor=" hero in heroes">
<td>{{hero.name}}</td>
</tr>
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr class="even">
<td>Superman</td>
</tr>
<tr class="odd">
<td>Batman</td>
</tr>
...
</tbody>
</table>
<tr *ngFor="let hero of heroes; let even = even; let odd = odd"
[ngClass]="{ odd: odd, even: even }">
<td>{{hero.name}}</td>
</tr>
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr class='first'>
<td>Superman</td>
</tr>
...
<tr class='last'>
<td>Flash</td>
</tr>
</tbody>
</table>
<tr *ngFor="let hero of heroes; let first = first; let last = last"
[ngClass]="{ first: first, last: last }">
<td>{{hero.name}}</td>
</tr>
import {Directive, Input} from "@angular/core";
@Directive({
selector: 'hero',
})
export class Hero {
@Input()
id: number;
@Input()
name:string;
}
<tr *ngFor="let hero of heroes; let i = index">
<td>{{hero.name}}</td>
<td>{{i}}</td>
</tr>
<table>
<thead>
<th>Name</th>
<th>Index</th>
</thead>
<tbody>
<tr>
<td>Superman</td>
<td>0</td>
</tr>
<tr>
<td>Batman</td>
<td>1</td>
</tr>
...
</tbody>
</table>
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr>
<td>Superman</td>
</tr>
<tr>
<td>Batman</td>
</tr>
...
</tbody>
</table>
@Component({
selector:'heroes',
template: `
<table>
<thead>
<th>Name</th>
</thead>
<tbody>
<tr *ngFor="let hero of heroes; trackBy: trackHero" >
<td>{{hero.name}}</td>
</tr>
</tbody>
</table>
`
})
export class Heroes {
heroes = HEROES;
trackHero(index, hero) {
console.log(hero);
return hero ? hero.id : undefined;
}
}
<tr *ngFor="let hero of heroes; trackBy hero?.id" >
<td>{{hero.name}}</td>
</tr>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment