import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: '<h1>{{ title }}</h1>'
})
export class AppComponent {
title = "My First Angular 2 App"
}
@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html'
})
export class HeroesComponent {
constructor(private _service: HeroService){ }
heroes:Hero[];
selectedHero: Hero;
selectHero(hero: Hero) { this.selectedHero = hero; }
}
export class HeroListComponent implements OnInit {
constructor(private _service: HeroService){ }
heroes:Hero[];
selectedHero: Hero;
ngOnInit(){
this.heroes = this._service.getHeroes();
}
selectHero(hero: Hero) { this.selectedHero = hero; }
}
<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>
<div *ngFor="#hero of heroes" (click)="selectHero(hero)">
{{hero.name}}
</div>
<hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>
@Component({
selector: 'hero-list',
templateUrl: 'app/hero-list.component.html',
directives: [HeroDetailComponent],
providers: [HeroService]
})
export class HeroesComponent { ... }
<hero-list></hero-list>
<div>{{hero.name}}</div>
<hero-detail [hero]="selectedHero"></hero-detail>
<div (click)="selectHero(hero)"></div>
<div (click)="selectHero(hero)"></div>
<hero-detail [hero]="selectedHero"></hero-detail>
<div>{{hero.name}}</div>
export class Logger {
log(msg: any) { console.log(msg); }
error(msg: any) { console.error(msg); }
warn(msg: any) { console.warn(msg); }
}
export class HeroService {
constructor(
private _backend: BackendService,
private _logger: Logger) { }
private _heroes:Hero[] = [];
getHeroes() {
this._backend.getAll(Hero).then( (heroes:Hero[]) => {
this._logger.log(`Fetched ${heroes.length} heroes.`);
this._heroes.push(...heroes); // fill cache
});
return this._heroes;
}
}
<input [(ngModel)]="hero.name">
<div *ngFor="#hero of heroes"></div>
<hero-detail *ngIf="selectedHero"></hero-detail>
constructor(private _service: HeroService){ }
---------------------------------------------
@Component({
providers: [HeroService]
})
export class HeroesComponent { ... }