Angular Abstract Form Base Component

JS
S
JavaScript

Simple snippet to use as a base for simple reactive forms

1import { Component, OnInit, Output, EventEmitter } from '@angular/core';
2
3import { ReactiveFormsModule, FormGroup, FormControl, Validators, FormArray, FormBuilder } from '@angular/forms';
4import { debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs/operators';
5
6@Component({
7  selector: 'app-form-base',
8  templateUrl: './form-base.component.html',
9  styleUrls: ['./form-base.component.scss']
10})
11export class FormBaseComponent implements OnInit {
12  @Output() formFilled: EventEmitter<any> = new EventEmitter();
13
14  // DM
15  public form: FormGroup;
16  public errorMessages = {
17    default: 'Please correct this input'
18  };
19
20  constructor() { }
21
22  ngOnInit() {
23  }
24
25  getErrorMessage(control: FormControl): string {
26    return (control.invalid && (control.dirty || control.touched)) ? this.errorMessages.default : '';
27  }
28  getErrorClass(control: FormControl): string {
29    return (control.invalid && (control.dirty || control.touched)) ? 'b--dark-red dark-red' : '';
30  }
31  hasError(control: FormControl): boolean {
32    return (control.invalid && (control.dirty || control.touched));
33  }
34  onFormFocusOut() {
35    Object.keys(this.form.controls).forEach(field => {
36      const control = this.form.get(field);
37      control.markAsTouched({ onlySelf: true });
38    });
39  }
40  subscribeToForm() {
41    this.form.valueChanges
42      .pipe(
43        debounceTime(400),
44        distinctUntilChanged(),
45        filter((data) => this.form.valid)
46      )
47      .subscribe((formData) => {
48        console.log('form safe and ready', formData);
49        this.formFilled.emit(formData);
50      });
51  }
52}
53
54
55// Usage
56constructor(fb: FormBuilder) {
57  super();
58  public title = new FormControl('', Validators.required);
59  this.form = fb.group({
60     title: this.title
61  });
62  this.subscribeToForm();
63}
64

Created on 7/30/2019