]> git.apps.os.sepia.ceph.com Git - ceph-ci.git/blob
3cc35df4d7bb5c35637ed088d11215f17d8d9726
[ceph-ci.git] /
1 import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
2 import { FormGroup } 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;
31   @Output() submitAction = new EventEmitter();
32
33   loading = false;
34
35   constructor(private elRef: ElementRef) {}
36
37   ngOnInit() {
38     this.form.statusChanges.subscribe(() => {
39       if (_.has(this.form.errors, 'cdSubmitButton')) {
40         this.loading = false;
41         _.unset(this.form.errors, 'cdSubmitButton');
42         this.form.updateValueAndValidity();
43       }
44     });
45   }
46
47   submit() {
48     this.focusButton();
49
50     if (this.form.invalid) {
51       this.focusInvalid();
52       return;
53     }
54
55     this.loading = true;
56     this.submitAction.emit();
57   }
58
59   focusButton() {
60     this.elRef.nativeElement.offsetParent.querySelector(
61       'button[type="submit"]'
62     ).focus();
63   }
64
65   focusInvalid() {
66     const target = this.elRef.nativeElement.offsetParent.querySelector(
67       'input.ng-invalid, select.ng-invalid'
68     );
69
70     if (target) {
71       target.focus();
72     }
73   }
74 }