/
app.ts
74 lines (68 loc) · 2.57 KB
/
app.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import {bootstrap, Component, FORM_DIRECTIVES, NgFor, NgIf, NgClass, Control, Validators, Observable} from 'angular2/angular2'
import {Http, Headers, HTTP_PROVIDERS} from 'angular2/http'
import {HeroesStore, Hero} from './HeroesStore'
import {HeroActions} from './HeroActions'
import {Dispatcher} from './Dispatcher'
@Component({
selector: 'my-app',
directives: [FORM_DIRECTIVES, NgFor, NgIf, NgClass],
styles: [`
.heroes {list-style-type: none; margin-left: 1em; padding: 0; width: 10em;}
.heroes li { cursor: pointer; position: relative; left: 0; transition: all 0.2s ease; }
.heroes li:hover {color: #369; background-color: #EEE; left: .2em;}
.heroes .badge {
font-size: small;
color: white;
padding: 0.1em 0.7em;
background-color: #369;
line-height: 1em;
position: relative;
left: -1px;
top: -1px;
}
.selected { background-color: #EEE; color: #369; }
`],
template: `
<h1>{{title}}</h1>
<ul class="heroes">
<li *ng-for="#hero of heroes" (click)="onSelect(hero)" [ng-class]="getSelectedClass(hero)">
<span class="badge">{{hero.id}}</span>{{hero.name}}
</li>
</ul>
<div *ng-if="selectedHero">
<form (submit)="updateHero($event, newName)">
<div><label>id: </label>{{selectedHero.id}}</div>
<div><label>name: </label>
<div><input type="text" placeholder="name" [ng-form-control]="newName"></div>
<p *ng-if="newName.hasError('required')">Name is required</p>
<button type="submit">Submit</button>
</form>
<h2>{{selectedHero.name}} details!</h2>
</div>
`
})
export class AppComponent {
title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;
newName: Control = new Control('', Validators.required);
constructor(private heroesStore: HeroesStore, private heroActions: HeroActions) {
this.heroesStore.subscribe(heroes => this.heroes = heroes);
this.heroes = heroesStore.state;
}
onSelect(hero: Hero) {
this.selectedHero = hero;
this.newName.updateValue(hero.name, true);
this.heroesStore.subscribe(heroes => console.log(heroes))
}
getSelectedClass(hero: Hero) {
return { 'selected': hero === this.selectedHero };
}
updateHero(event, newName) {
event.preventDefault();
this.heroActions.updateHero(
new Hero(this.selectedHero.id, newName.value)
);
}
}
bootstrap(AppComponent, [HTTP_PROVIDERS, HeroesStore, HeroActions, Dispatcher])