Home > front end >  Angular - using a date pipe with ngModel
Angular - using a date pipe with ngModel

Time:02-08

I am getting the following error in my console - "Error: InvalidPipeArgument: 'Unable to convert "[object Object]" into a date' for pipe 'DatePipe'".

I have a calendar input, which should allow the user to select a date and then pass on that date in a certain format, 'dd/MM/yyyy'. I want the date selected to show in the calendar input once they have selected a date.

I realise I cannot have two way binding on the [ngModel] if I have a pipe there so I'm using (ngModelChange). If I remove the #createdByCutOffDate="ngModel" then the error is removed but I cannot see the selected date show in the calendar input.

I also tried the updateCreatedByCutOffDate() method taking a date type or string.

this.createdByCutOffDate is in the following format - 'Thu Feb 17 2022 00:00:00 GMT 0000 (Greenwich Mean Time)'

component.html


<input type="date"
       id="createdByCutOffDate"
       [ngModel]="createdByCutOffDate | date:'dd/MM/yyyy'"
       #createdByCutOffDate="ngModel"
       (ngModelChange)="updateCreatedByCutOffDate($event)" />

component.ts


createdByCutOffDate: Date;

updateCreatedByCutOffDate(date: string) {
    this.createdByCutOffDate = new Date(date);

    }

CodePudding user response:

createdByCutOffDate is a Date object that has its methods and properties.
So to solve your problem, use "createdByCutOffDate.date | date:'dd/MM/yyyy'" instead of "createdByCutOffDate | date:'dd/MM/yyyy'"

  •  Tags:  
  • Related