emmaakachukwu
emmaakachukwu

Reputation: 625

How to format angular mat date picker value

I am using a mat date picker in my form and saving the value to my database. The value saves in this format: 2019-08-22T23:00:00. I am fetching back these values from the database and binding them to form inputs using ngModel but i am having problem binding the date to the mat date picker.

Here is my HTML:

<mat-form-field>
   <input matInput [matDatepicker]="picker" placeholder="Date of birth" 
   [ngModel]="user.dob | date " name='dob'>
   <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
   <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

I send the value from the above to a mysql database. I noticed that when i choose a date like 23rd August, 2019, it returns 22nd in this format 2019-08-22T23:00:00. When I fetch back the data from my database and try to bind it to the date type input field above, it does not bind. How to make the date picker return the selected date and also how to bind the date to it in the format dd-mm-yy. Thanks.

Upvotes: 0

Views: 5789

Answers (1)

chrismclarke
chrismclarke

Reputation: 2105

The easiest way to do this is use a form control. This can be bound either to the value field or a formControl field, i.e.:

@Component({
  selector: 'datepicker-value-example',
  templateUrl: 'datepicker-value-example.html',
  styleUrls: ['datepicker-value-example.css'],
})
export class DatepickerValueExample {
  date = new FormControl('2019-08-22T23:00:00');
}

AppComponent.ts

<mat-form-field>
  <input matInput [matDatepicker]="picker1" placeholder="Angular forms" [formControl]="date">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1></mat-datepicker>
</mat-form-field>

<mat-form-field>
  <input matInput [matDatepicker]="picker3" placeholder="Value binding" [value]="date.value">
  <mat-datepicker-toggle matSuffix [for]="picker3"></mat-datepicker-toggle>
  <mat-datepicker #picker3></mat-datepicker>
</mat-form-field>

AppComponent.html

You can see a working blitz here: https://stackblitz.com/edit/angular-umwtzi?file=app%2Fdatepicker-value-example.html

Or more documentation and examples from the material docs: https://material.angular.io/components/datepicker/examples

Upvotes: 3

Related Questions