How can date and timestamp be shown in Angular using Ngrx and Reactive Form

1.4k Views Asked by At

I have complex graph and I want to create a reactive with form builder and pass the object in form builder

this.objectForm = this.formBuilder.group({
                    ...this.object
                  });

I received the date from back-end in UTC format (e.g. 2011-08-12T20:17:46.384Z). I want to show only the date in mat-input field but when user focus out his date and time, both should be saved in store. I don't want to show time to user, but I want it saved in database and Ngrx Store.

Below is the HTML code:

<input matInput type="date" formControlName="SelectedDate" name="SelectedDate" id="SelectedDate" 
dateTime>

Used different technique e.g. Build custom pipe and custom directive but result is not shown in desired format. formControlName (used in above mentioned HTML) accept only string in angular 8 and type='date' only accept date not time.

Below is the code we are trying till now:

import {Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
import {NgControl, NgModel} from '@angular/forms';
import {DatePipe, DecimalPipe} from '@angular/common';

@Directive({
  selector: '[dateTime][formControlName]',
})
export class DateTime {


  constructor(private el: ElementRef, public datePipe: DatePipe, private model: NgControl) {
  }

  ngOnInit() {
    this.el.nativeElement.value = this.datePipe.transform(this.model.control.value, 'yyyy-MM-dd');
    this.model.viewToModelUpdate(this.el.nativeElement.value);
  }


  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {

  }

  @HostListener('focusout')
  focusOUt() {
    let date: Date = new Date(this.el.nativeElement.value);
  }
}
1

There are 1 best solutions below

0
On

If you are OK with loosing the original time (since you're anyway not showing it to the user) I'd just convert it to string during the form creation and then use (new Date(form.value.SelectedDate)).toUTCString() to convert it back to full UTC for back-end.

If original time is important, then split the datetime in SelectedDate and SelectedTime. You can then handle SelectedDate separately in you mat-input and on save combine it with SelectedTime before sending back to back-end.