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