1

I have this calendar that i want to display the default value of user's previously input date. However it does not display any value when I try to change the date. New date is still being able to save so I'm curious how to fix the displaying on data change.

Here is the code for reference

<mat-form-field>
  <input matInput [matDatepicker]="dp" placeholder="Date of Birth: No change Display" [formControl]="getDate(userPrivate.date_of_birth)" [(ngModel)]="userPrivate.date_of_birth">
  <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
  <mat-datepicker #dp >
  </mat-datepicker>
</mat-form-field>

and on my .ts

getDate(x){
  // convert Epoch time to formcontrol
  var date = new FormControl(new Date(parseInt(x)));
  // return newDate;
  return date;
  }
Anas
  • 971
  • 13
  • 28
Monomoni
  • 415
  • 2
  • 4
  • 19
  • patch the form control, why are you using ngModel with formControl? – Robert Oct 03 '19 at 09:48
  • That is because I'm still fairly new to angular and trying out reactive form for the first time using the guide from https://material.angular.io/components/datepicker/overview and added my own ngModel to get the data value. Will look into patchvalue – Monomoni Oct 03 '19 at 10:05

1 Answers1

0

This is what I've done when I was working with mat-datepicker

<input matInput [matDatepicker]="dp" placeholder="Choose a date" [formControl]="dateForm" (click)="dp.open()"
        (dateChange)="dateChange($event)" #dateInput>
    <mat-datepicker #dp></mat-datepicker>

In .ts, I'm using moment library to set the date to the formcontrol

this.dateForm.setValue(moment(previous_input_date, date_format));
Chandra Kanth
  • 348
  • 2
  • 13
  • 1
    That's a good tip. In the above example, I'm using *event binding* on the (dateChange) event, as per the material documentation https://material.angular.io/components/datepicker/api – Chandra Kanth Oct 04 '19 at 05:03
  • Now that i looked in depth, you're perfectly right. – Robert Oct 04 '19 at 07:57