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 {
31 form: FormGroup | NgForm;
35 submitAction = new EventEmitter();
41 constructor(private elRef: ElementRef) {}
44 this.form.statusChanges.subscribe(() => {
45 if (_.has(this.form.errors, 'cdSubmitButton')) {
47 _.unset(this.form.errors, 'cdSubmitButton');
48 // Handle Reactive forms.
49 if (this.form instanceof AbstractControl) {
50 (<AbstractControl>this.form).updateValueAndValidity();
59 // Special handling for Template driven forms.
60 if (this.form instanceof FormGroupDirective) {
61 (<FormGroupDirective>this.form).onSubmit($event);
64 if (this.form.invalid) {
70 this.submitAction.emit();
74 this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
78 const target = this.elRef.nativeElement.offsetParent.querySelector(
79 'input.ng-invalid, select.ng-invalid'