1 import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
2 import { AbstractControl, FormGroup, FormGroupDirective, NgForm } from '@angular/forms';
4 import * as _ from 'lodash';
7 * This component will render a submit button with the given label.
9 * The button will disabled itself and show a loading icon when the user clicks
10 * it, usually initiating a request to the server, and it will stay in that
11 * state until the request is finished.
13 * To indicate that the request failed, returning the button to the enable
14 * state, you need to insert an error in the form with the 'cdSubmitButton' key.
15 * p.e.: this.rbdForm.setErrors({'cdSubmitButton': true});
17 * It will also check if the form is valid, when clicking the button, and will
18 * focus on the first invalid input.
21 * @class SubmitButtonComponent
22 * @implements {OnInit}
25 selector: 'cd-submit-button',
26 templateUrl: './submit-button.component.html',
27 styleUrls: ['./submit-button.component.scss']
29 export class SubmitButtonComponent implements OnInit {
30 @Input() form: FormGroup | NgForm;
31 @Input() type = 'submit';
32 @Output() submitAction = new EventEmitter();
36 constructor(private elRef: ElementRef) {}
39 this.form.statusChanges.subscribe(() => {
40 if (_.has(this.form.errors, 'cdSubmitButton')) {
42 _.unset(this.form.errors, 'cdSubmitButton');
43 // Handle Reactive forms.
44 if (this.form instanceof AbstractControl) {
45 (<AbstractControl>this.form).updateValueAndValidity();
54 // Special handling for Template driven forms.
55 if (this.form instanceof FormGroupDirective) {
56 (<FormGroupDirective>this.form).onSubmit($event);
59 if (this.form.invalid) {
65 this.submitAction.emit();
69 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
73 const target = this.elRef.nativeElement.offsetParent.querySelector(
74 'input.ng-invalid, select.ng-invalid'