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;
36 submitAction = new EventEmitter();
43 constructor(private elRef: ElementRef) {}
46 this.form.statusChanges.subscribe(() => {
47 if (_.has(this.form.errors, 'cdSubmitButton')) {
49 _.unset(this.form.errors, 'cdSubmitButton');
50 // Handle Reactive forms.
51 if (this.form instanceof AbstractControl) {
52 (<AbstractControl>this.form).updateValueAndValidity();
61 // Special handling for Template driven forms.
62 if (this.form instanceof FormGroupDirective) {
63 (<FormGroupDirective>this.form).onSubmit($event);
66 if (this.form.invalid) {
72 this.submitAction.emit();
76 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
80 const target = this.elRef.nativeElement.offsetParent.querySelector(
81 'input.ng-invalid, select.ng-invalid'