Guest User

Untitled

a guest
Jun 21st, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. import { Component, OnInit, OnChanges, SimpleChanges, Output, EventEmitter, Input } from '@angular/core';
  2. import { FormGroup, FormControl } from '@angular/forms';
  3. import { distinctUntilChanged } from 'rxjs/operators';
  4. import { Action } from '@ngrx/store';
  5. import { IFormState } from '../state/application-state';
  6. import { formNameChanged } from '../actions';
  7.  
  8. @Component({
  9. selector: 'piotrek-form',
  10. templateUrl: './form.component.html',
  11. styleUrls: ['./form.component.css']
  12. })
  13. export class FormComponent implements OnInit, OnChanges {
  14.  
  15. constructor() { }
  16.  
  17. @Input() form: IFormState; // We pass the form's state as the input
  18. @Output() actionsEmitted: EventEmitter<Action[]> = new EventEmitter(); // ...and emit actions that should change the state.
  19.  
  20. myForm: FormGroup = new FormGroup({
  21. name: new FormControl('', {
  22. //micro-optimization: the event on valueChanges stream will be fired only on focus-out, instead of every key press
  23. updateOn: 'blur'
  24. })
  25. });
  26.  
  27. ngOnInit() {
  28. // subscribe to disting value changes on each control and emit the event with action as payload
  29. this.myForm.controls['name'].valueChanges.pipe(distinctUntilChanged()).subscribe((value) => {
  30. this.actionsEmitted.emit([formNameChanged(value)]);
  31. });
  32. }
  33.  
  34. ngOnChanges(changes: SimpleChanges) {
  35. if(!changes.form || changes.form.isFirstChange()) {
  36. return;
  37. }
  38.  
  39. // whenever input changes (and input is the form's state in the store), we update the value of the control
  40. this.myForm.controls['name'].setValue(changes.form.currentValue.name);
  41. }
  42.  
  43. }
Add Comment
Please, Sign In to add comment