1 import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
2 import { AbstractControl, FormGroup, FormGroupDirective, NgForm } from '@angular/forms';
3 import { Icons } from '../../../shared/enum/icons.enum';
5 import * as _ from 'lodash';
8 * This component will render a submit button with the given label.
10 * The button will disabled itself and show a loading icon when the user clicks
11 * it, usually initiating a request to the server, and it will stay in that
12 * state until the request is finished.
14 * To indicate that the request failed, returning the button to the enable
15 * state, you need to insert an error in the form with the 'cdSubmitButton' key.
16 * p.e.: this.rbdForm.setErrors({'cdSubmitButton': true});
18 * It will also check if the form is valid, when clicking the button, and will
19 * focus on the first invalid input.
22 * @class SubmitButtonComponent
23 * @implements {OnInit}
26 selector: 'cd-submit-button',
27 templateUrl: './submit-button.component.html',
28 styleUrls: ['./submit-button.component.scss']
30 export class SubmitButtonComponent implements OnInit {
32 form: FormGroup | NgForm;
40 // A CSS class string to apply to the button's main element.
45 submitAction = new EventEmitter();
50 constructor(private elRef: ElementRef) {}
53 this.form.statusChanges.subscribe(() => {
54 if (_.has(this.form.errors, 'cdSubmitButton')) {
56 _.unset(this.form.errors, 'cdSubmitButton');
57 // Handle Reactive forms.
58 if (this.form instanceof AbstractControl) {
59 (<AbstractControl>this.form).updateValueAndValidity();
68 // Special handling for Template driven forms.
69 if (this.form instanceof FormGroupDirective) {
70 (<FormGroupDirective>this.form).onSubmit($event);
73 if (this.form.invalid) {
79 this.submitAction.emit();
83 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
87 const target = this.elRef.nativeElement.offsetParent.querySelector(
88 'input.ng-invalid, select.ng-invalid'