LP#1775466 Angular(6) base application
[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
22     current: NgbDateStruct;
23
24     @Output() onChangeAsDate: EventEmitter<Date>;
25     @Output() onChangeAsIso: EventEmitter<string>;
26     @Output() onChangeAsYmd: EventEmitter<string>;
27
28     constructor() {
29         this.onChangeAsDate = new EventEmitter<Date>();
30         this.onChangeAsIso = new EventEmitter<string>();
31         this.onChangeAsYmd = new EventEmitter<string>();
32     }
33
34     ngOnInit() {
35
36         if (this.initialYmd) {
37             this.initialDate = this.localDateFromYmd(this.initialYmd);
38
39         } else if (this.initialIso) {
40             this.initialDate = new Date(this.initialIso);
41         }
42
43         if (this.initialDate) {
44             this.current = {
45                 year: this.initialDate.getFullYear(),
46                 month: this.initialDate.getMonth() + 1,
47                 day: this.initialDate.getDate()
48             };
49         }
50     }
51
52     onDateSelect(evt) {
53         const ymd = `${evt.year}-${evt.month}-${evt.day}`;
54         const date = this.localDateFromYmd(ymd);
55         const iso = date.toISOString();
56         this.onChangeAsDate.emit(date);
57         this.onChangeAsYmd.emit(ymd);
58         this.onChangeAsIso.emit(iso);
59     }
60
61     // Create a date in the local time zone with selected YMD values.
62     // TODO: Consider moving this to a date service...
63     localDateFromYmd(ymd: string): Date {
64         const parts = ymd.split('-');
65         return new Date(
66             Number(parts[0]), Number(parts[1]) - 1, Number(parts[2]));
67     }
68 }
69
70