Reputation: 89
In my angular 4 project, I have a datepicker in my html.
In html:
<mat-form-field class="col-sm-12 nopadding pull-left">
<input matInput [matDatepicker]="date" placeholder="Please select a date" [(ngModel)]="txtDate">
<mat-datepicker-toggle matSuffix [for]="date"></mat-datepicker-toggle>
<mat-datepicker #date></mat-datepicker>
</mat-form-field>
Im able to select date and convert it into dd/mm/yyyy format in my DB. When i retrieve date im converting it back to MM/DD/YYYY (the format in which my datepicker works) I am getting the value from web api and in console i can see the value is converted correctly and assigned to the ngModel. But its not displaying in the datepicker field
In ts file
var dateParts = result.Date.split("/");
var dateObject = new Date(dateParts [2], dateParts [1] - 1, dateParts [0]);
this.txtDate=moment(dateObject ).format('MM/DD/YYYY'); -- output of this in console is 11/14/2018 (the desired output)
but the same is not displaying in date-picker. can you please help!!
Upvotes: 0
Views: 1770
Reputation: 74738
I would rather suggest you to create a custom pipe:
[(ngModel)]="txtDate | dateformatter:'MM/DD/YYYY'"
import {
Pipe,
PipeTransform
} from '@angular/core';
@Pipe({ name: 'dateformatter' })
export class DateFormatterPipe implements PipeTransform {
transform(value: number, dateformat: string): string {
var dateParts = result.Date.split("/");
var dateObject = new Date(dateParts [2], dateParts [1] - 1, dateParts [0]);
return moment(dateObject).format(dateformat.toUpperCase());
}
}
Or you can take a look into a date
pipe:
[(ngModel)]="txtDate | date:'shortDate'"
Upvotes: 1