Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. import { Component, OnInit } from '@angular/core';
  2. import { FormGroup, FormBuilder, Validators } from '@angular/forms';
  3. import { Hero } from '../shared/hero';
  4. import { forbiddenNameValidator } from '../shared/forbidden-name.directive';
  5. @Component({
  6. moduleId: module.id,
  7. selector: 'hero-form-reactive3',
  8. templateUrl: 'hero-form-reactive.component.html'
  9. })
  10. export class HeroFormReactiveComponent implements OnInit {
  11. powers = ['Really Smart', 'Super Flexible', 'Weather Changer'];
  12. hero = new Hero(18, 'Dr. WhatIsHisName', this.powers[0], 'Dr. What');
  13. submitted = false;
  14. onSubmit() {
  15. this.submitted = true;
  16. this.hero = this.heroForm.value;
  17. }
  18. addHero() {
  19. this.hero = new Hero(42, '', '');
  20. this.buildForm();
  21. this.active = false;
  22. setTimeout(() => this.active = true, 0);
  23. }
  24. heroForm: FormGroup;
  25. constructor(private fb: FormBuilder) { }
  26. ngOnInit(): void {
  27. this.buildForm();
  28. }
  29. buildForm(): void {
  30. this.heroForm = this.fb.group({
  31. 'name': [this.hero.name, [
  32. Validators.required,
  33. Validators.minLength(4),
  34. Validators.maxLength(24),
  35. forbiddenNameValidator(/bob/i)
  36. ]
  37. ],
  38. 'alterEgo': [this.hero.alterEgo],
  39. 'power': [this.hero.power, Validators.required]
  40. });
  41. this.heroForm.valueChanges
  42. .subscribe(data => this.onValueChanged(data));
  43. this.onValueChanged(); // (re)set validation messages now
  44. }
  45. onValueChanged(data?: any) {
  46. if (!this.heroForm) { return; }
  47. const form = this.heroForm;
  48. for (const field in this.formErrors) {
  49. // clear previous error message (if any)
  50. this.formErrors[field] = '';
  51. const control = form.get(field);
  52. if (control && control.dirty && !control.valid) {
  53. const messages = this.validationMessages[field];
  54. for (const key in control.errors) {
  55. this.formErrors[field] += messages[key] + ' ';
  56. }
  57. }
  58. }
  59. }
  60. formErrors = {
  61. 'name': '',
  62. 'power': ''
  63. };
  64. validationMessages = {
  65. 'name': {
  66. 'required': 'Name is required.',
  67. 'minlength': 'Name must be at least 4 characters long.',
  68. 'maxlength': 'Name cannot be more than 24 characters long.',
  69. 'forbiddenName': 'Someone named "Bob" cannot be a hero.'
  70. },
  71. 'power': {
  72. 'required': 'Power is required.'
  73. }
  74. };
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement