|
| 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/observable/of'; |
| 7 | +import 'rxjs/add/operator/debounceTime'; |
| 8 | +import 'rxjs/add/operator/do'; |
| 9 | +import { Component, OnInit, OnDestroy, AfterViewInit, ViewChildren, ElementRef } from '@angular/core'; |
| 10 | +import { FormBuilder, FormGroup, FormControlName, Validators } from '@angular/forms'; |
| 11 | +import { Observable } from 'rxjs/Observable'; |
| 12 | +import { Subscription } from 'rxjs/Subscription'; |
| 13 | + |
| 14 | +import { HeroService } from './hero.service'; |
| 15 | + |
| 16 | +@Component({ |
| 17 | + moduleId: module.id, |
| 18 | + templateUrl: 'add-hero.component.html', |
| 19 | + styles: [ '.error { color: red }' ] |
| 20 | +}) |
| 21 | +export class AddHeroComponent implements OnInit, OnDestroy, AfterViewInit { |
| 22 | + @ViewChildren(FormControlName, { read: ElementRef }) formControls: ElementRef[]; |
| 23 | + |
| 24 | + form: FormGroup; |
| 25 | + sub: Subscription; |
| 26 | + showErrors: boolean = false; |
| 27 | + submitted: boolean = false; |
| 28 | + success: boolean; |
| 29 | + |
| 30 | + constructor( |
| 31 | + private formBuilder: FormBuilder, |
| 32 | + private heroService: HeroService |
| 33 | + ) {} |
| 34 | + |
| 35 | + ngOnInit() { |
| 36 | + this.form = this.formBuilder.group({ |
| 37 | + name: ['', [Validators.required]], |
| 38 | + description: [''] |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + ngAfterViewInit() { |
| 43 | + const controlBlurs: Observable<Event>[] = this.formControls.map(field => Observable.fromEvent(field.nativeElement, 'blur')); |
| 44 | + |
| 45 | + this.sub = Observable.merge( |
| 46 | + this.form.valueChanges, |
| 47 | + ...controlBlurs |
| 48 | + ) |
| 49 | + .debounceTime(300) |
| 50 | + .subscribe(() => this.checkErrors()); |
| 51 | + } |
| 52 | + |
| 53 | + checkErrors() { |
| 54 | + if (!this.form.valid) { |
| 55 | + this.showErrors = true; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + save(model: any) { |
| 60 | + this.success = false; |
| 61 | + this.submitted = true; |
| 62 | + |
| 63 | + this.heroService.addHero(model) |
| 64 | + .do(() => { |
| 65 | + this.success = true; |
| 66 | + this.submitted = false; |
| 67 | + }) |
| 68 | + .subscribe(); |
| 69 | + } |
| 70 | + |
| 71 | + ngOnDestroy() { |
| 72 | + this.sub.unsubscribe(); |
| 73 | + } |
| 74 | +} |
0 commit comments