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