1 import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
2 import { AbstractControl, FormGroup, FormGroupDirective, NgForm } from '@angular/forms';
4 import _ from 'lodash';
6 import { Icons } from '~/app/shared/enum/icons.enum';
9 * This component will render a submit button with the given label.
11 * The button will disabled itself and show a loading icon when the user clicks
12 * it, usually initiating a request to the server, and it will stay in that
13 * state until the request is finished.
15 * To indicate that the request failed, returning the button to the enable
16 * state, you need to insert an error in the form with the 'cdSubmitButton' key.
17 * p.e.: this.rbdForm.setErrors({'cdSubmitButton': true});
19 * It will also check if the form is valid, when clicking the button, and will
20 * focus on the first invalid input.
23 * @class SubmitButtonComponent
24 * @implements {OnInit}
27 selector: 'cd-submit-button',
28 templateUrl: './submit-button.component.html',
29 styleUrls: ['./submit-button.component.scss']
31 export class SubmitButtonComponent implements OnInit {
33 form: FormGroup | NgForm;
41 // A CSS class string to apply to the button's main element.
49 submitAction = new EventEmitter();
54 constructor(private elRef: ElementRef) {}
57 this.form.statusChanges.subscribe(() => {
58 if (_.has(this.form.errors, 'cdSubmitButton')) {
60 _.unset(this.form.errors, 'cdSubmitButton');
61 // Handle Reactive forms.
62 if (this.form instanceof AbstractControl) {
63 (<AbstractControl>this.form).updateValueAndValidity();
72 // Special handling for Template driven forms.
73 if (this.form instanceof FormGroupDirective) {
74 (<FormGroupDirective>this.form).onSubmit($event);
77 if (this.form.invalid) {
83 this.submitAction.emit();
87 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
91 const target = this.elRef.nativeElement.offsetParent.querySelector(
92 'input.ng-invalid, select.ng-invalid'