]> git.apps.os.sepia.ceph.com Git - ceph.git/blob
5d62b892dd6acdf57600137dc660c1ad2839dc2b
[ceph.git] /
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';
4
5 import * as _ from 'lodash';
6
7 /**
8  * This component will render a submit button with the given label.
9  *
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.
13  *
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});
17  *
18  * It will also check if the form is valid, when clicking the button, and will
19  * focus on the first invalid input.
20  *
21  * @export
22  * @class SubmitButtonComponent
23  * @implements {OnInit}
24  */
25 @Component({
26   selector: 'cd-submit-button',
27   templateUrl: './submit-button.component.html',
28   styleUrls: ['./submit-button.component.scss']
29 })
30 export class SubmitButtonComponent implements OnInit {
31   @Input()
32   form: FormGroup | NgForm;
33   @Input()
34   type = 'submit';
35   @Output()
36   submitAction = new EventEmitter();
37   @Input()
38   disabled = false;
39
40   loading = false;
41   icons = Icons;
42
43   constructor(private elRef: ElementRef) {}
44
45   ngOnInit() {
46     this.form.statusChanges.subscribe(() => {
47       if (_.has(this.form.errors, 'cdSubmitButton')) {
48         this.loading = false;
49         _.unset(this.form.errors, 'cdSubmitButton');
50         // Handle Reactive forms.
51         if (this.form instanceof AbstractControl) {
52           (<AbstractControl>this.form).updateValueAndValidity();
53         }
54       }
55     });
56   }
57
58   submit($event: any) {
59     this.focusButton();
60
61     // Special handling for Template driven forms.
62     if (this.form instanceof FormGroupDirective) {
63       (<FormGroupDirective>this.form).onSubmit($event);
64     }
65
66     if (this.form.invalid) {
67       this.focusInvalid();
68       return;
69     }
70
71     this.loading = true;
72     this.submitAction.emit();
73   }
74
75   focusButton() {
76     this.elRef.nativeElement.offsetParent.querySelector(`button[type="${this.type}"]`).focus();
77   }
78
79   focusInvalid() {
80     const target = this.elRef.nativeElement.offsetParent.querySelector(
81       'input.ng-invalid, select.ng-invalid'
82     );
83
84     if (target) {
85       target.focus();
86     }
87   }
88 }