in my input the date are being displayed via ngModel , is there a way we can format the date into date:'MM/dd/YYYY' via or through ng model[(ngModel)]="data.targetDate | date:'MM/dd/YYYY' "
? is this even possible ?
or can we format it like calling a method from ngModel like
[ngModel]="formatDate(data.targetDate)"
Thanks for help and ideas.
#html code
<input [ngModel]="data.targetDate" [matDatepicker]="pickerTargetDate">
CodePudding user response:
As far as I can tell from their docs and usages in our project, a date pipe cannot be used inside of the input in the HTML as it is supposed to be used in the template itself.
However, you can import the date pipe in your actual component itself and use its transform method to set your model's value, ex:
var datePipe = new DatePipe();
data.targetDate = datePipe.transform(userdate, 'MM/DD/YYYY');
Edit:
That said, per this SO post (Is there any way to change input type="date" format?) I do question whether that will work fully since an input's date value per spec should be a full date of format yyyy-mm-dd
. That said, a browser can display dates however it sees fit so it may still work.
Edit 2:
Made a small stackblitz, but component code is:
import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
myDate = new Date();
dateString: string;
ngOnInit() {
let datePipe = new DatePipe('en-US');
this.dateString = datePipe.transform(new Date(), 'yyyy-MM-dd');
console.log('Date string: ', this.dateString);
} }
HTML code is just:
<input [ngModel]='dateString'>
and it seems to work, so the transform has to be in that specific shape instead when doing it from code. One thing to bear in mind is that transform returns a string instead of a date