This repository was archived by the owner on Dec 4, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 877
/
Copy pathadd-hero.component.2.ts
74 lines (64 loc) · 1.85 KB
/
add-hero.component.2.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
// #docplaster
// #docregion
// #docregion rxjs-imports-1
import 'rxjs/add/operator/takeUntil';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/fromEvent';
// #enddocregion rxjs-imports-1
// #docregion viewchild-imports
import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
// #enddocregion viewchild-imports
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Hero } from './hero';
import { HeroService } from './hero.service';
// #docregion rxjs-imports-2
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// #enddocregion rxjs-imports-2
// #docregion viewchild-heroName
@Component({
moduleId: module.id,
templateUrl: './add-hero.component.html',
styles: [ '.error { color: red }' ]
})
export class AddHeroComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('heroName', { read: ElementRef }) heroName: ElementRef;
// #enddocregion viewchild-heroName
form: FormGroup;
showErrors: boolean = false;
success: boolean;
onDestroy$ = new Subject();
constructor(
private formBuilder: FormBuilder,
private heroService: HeroService
) {}
ngOnInit() {
this.form = this.formBuilder.group({
name: ['', [Validators.required]]
});
}
// #docregion observable-event
ngAfterViewInit() {
const controlBlur$: Observable<Event> = Observable.fromEvent(this.heroName.nativeElement, 'blur');
Observable.merge(
controlBlur$
)
.takeUntil(this.onDestroy$)
.subscribe(() => this.checkForm());
}
checkForm() {
if (!this.form.valid) {
this.showErrors = true;
}
}
// #enddocregion observable-event
ngOnDestroy() {
this.onDestroy$.complete();
}
save(model: Hero) {
this.heroService.addHero(model.name)
.subscribe(() => {
this.success = true;
});
}
}