|
| 1 | +// #docplaster |
| 2 | +// #docregion |
| 3 | +import 'rxjs/add/observable/of'; |
| 4 | +import 'rxjs/add/observable/fromEvent'; |
| 5 | +import 'rxjs/add/observable/merge'; |
| 6 | +import 'rxjs/add/operator/debounceTime'; |
| 7 | +import 'rxjs/add/operator/do'; |
| 8 | +import 'rxjs/add/operator/switchMap'; |
| 9 | +import 'rxjs/add/operator/take'; |
| 10 | +import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; |
| 11 | +import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms'; |
| 12 | +import { Observable } from 'rxjs/Observable'; |
| 13 | +import { Subject } from 'rxjs/Subject'; |
| 14 | + |
| 15 | +import { EventAggregatorService } from './event-aggregator.service'; |
| 16 | +import { HeroService } from './hero.service'; |
| 17 | + |
| 18 | +@Component({ |
| 19 | + moduleId: module.id, |
| 20 | + templateUrl: 'add-hero.component.html', |
| 21 | + styles: [ '.error { color: red }' ] |
| 22 | +}) |
| 23 | +export class AddHeroComponent implements OnInit, OnDestroy, AfterViewInit { |
| 24 | + @ViewChild('heroName', { read: ElementRef }) heroName: ElementRef; |
| 25 | + |
| 26 | + form: FormGroup; |
| 27 | + onDestroy$ = new Subject(); |
| 28 | + showErrors: boolean = false; |
| 29 | + success: boolean; |
| 30 | + |
| 31 | + constructor( |
| 32 | + private formBuilder: FormBuilder, |
| 33 | + private heroService: HeroService, |
| 34 | + private eventService: EventAggregatorService |
| 35 | + ) {} |
| 36 | + |
| 37 | + ngOnInit() { |
| 38 | + this.form = this.formBuilder.group({ |
| 39 | + name: ['', [Validators.required], [(control: FormControl) => { |
| 40 | + return this.checkHeroName(control.value); |
| 41 | + }]] |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + checkHeroName(name: string) { |
| 46 | + return Observable.of(name) |
| 47 | + .switchMap(heroName => this.heroService.isNameAvailable(heroName)) |
| 48 | + .map(available => available ? null : { taken: true }); |
| 49 | + } |
| 50 | + |
| 51 | + ngAfterViewInit() { |
| 52 | + const controlBlur$ = Observable.fromEvent(this.heroName.nativeElement, 'blur'); |
| 53 | + |
| 54 | + Observable.merge( |
| 55 | + this.form.valueChanges, |
| 56 | + controlBlur$ |
| 57 | + ) |
| 58 | + .debounceTime(300) |
| 59 | + .takeUntil(this.onDestroy$) |
| 60 | + .subscribe(() => this.checkErrors()); |
| 61 | + } |
| 62 | + |
| 63 | + checkErrors() { |
| 64 | + if (!this.form.valid) { |
| 65 | + this.showErrors = true; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + save(model: any) { |
| 70 | + this.heroService.addHero(model.name) |
| 71 | + .subscribe(() => { |
| 72 | + this.success = true; |
| 73 | + this.eventService.add({ |
| 74 | + type: 'hero', |
| 75 | + message: 'Hero Added' |
| 76 | + }); |
| 77 | + }); |
| 78 | + } |
| 79 | + |
| 80 | + ngOnDestroy() { |
| 81 | + this.onDestroy$.complete(); |
| 82 | + } |
| 83 | +} |
0 commit comments