LP1806087 Angular staff catalog phase II.
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / date-select / date-select.component.ts
1 import {Component, OnInit, Input, Output, ViewChild, EventEmitter} from '@angular/core';
2 import {NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';
3
4 /**
5  * RE: displaying locale dates in the input field:
6  * https://github.com/ng-bootstrap/ng-bootstrap/issues/754
7  * https://stackoverflow.com/questions/40664523/angular2-ngbdatepicker-how-to-format-date-in-inputfield
8  */
9
10 @Component({
11   selector: 'eg-date-select',
12   templateUrl: './date-select.component.html'
13 })
14 export class DateSelectComponent implements OnInit {
15
16     @Input() initialIso: string; // ISO string
17     @Input() initialYmd: string; // YYYY-MM-DD (uses local time zone)
18     @Input() initialDate: Date;  // Date object
19     @Input() required: boolean;
20     @Input() fieldName: string;
21     @Input() domId = '';
22
23     _disabled: boolean;
24     @Input() set disabled(d: boolean) {
25         this._disabled = d;
26     }
27
28     current: NgbDateStruct;
29
30     @Output() onChangeAsDate: EventEmitter<Date>;
31     @Output() onChangeAsIso: EventEmitter<string>;
32     @Output() onChangeAsYmd: EventEmitter<string>;
33
34     constructor() {
35         this.onChangeAsDate = new EventEmitter<Date>();
36         this.onChangeAsIso = new EventEmitter<string>();
37         this.onChangeAsYmd = new EventEmitter<string>();
38     }
39
40     ngOnInit() {
41
42         if (this.initialYmd) {
43             this.initialDate = this.localDateFromYmd(this.initialYmd);
44
45         } else if (this.initialIso) {
46             this.initialDate = new Date(this.initialIso);
47         }
48
49         if (this.initialDate) {
50             this.current = {
51                 year: this.initialDate.getFullYear(),
52                 month: this.initialDate.getMonth() + 1,
53                 day: this.initialDate.getDate()
54             };
55         }
56     }
57
58     onDateSelect(evt) {
59         const ymd = `${evt.year}-${evt.month}-${evt.day}`;
60         const date = this.localDateFromYmd(ymd);
61         const iso = date.toISOString();
62         this.onChangeAsDate.emit(date);
63         this.onChangeAsYmd.emit(ymd);
64         this.onChangeAsIso.emit(iso);
65     }
66
67     // Create a date in the local time zone with selected YMD values.
68     // TODO: Consider moving this to a date service...
69     localDateFromYmd(ymd: string): Date {
70         const parts = ymd.split('-');
71         return new Date(
72             Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
73     }
74 }
75
76