ng2-datepicker with format option and ngModel returning [object Object]

7.5k Views Asked by At

I'm trying to use the ng2-datepicker for choosing a date and afterwards displaying it on a table. I'm having the issue that the binding to my chosen date doesn't work. I guess that it has to do something with the format option that I made (DD.MM.YYYY). In my html, I have this code:

<ng2-datepicker [(ngModel)]="date" [options]="datepickeroptions"></ng2-datepicker>

datepickeroptions with typescript is like this:

this.datepickeroptions = {
  format: "DD.MM.YYYY",
  locale: "de",
};

I tried to initialize the date variable as Date and as string, but none of them worked. I get just [object Object] as value from ngModel although the value in the input container looks ok. Thanks in advance for your help.

object Object in parent container

2

There are 2 best solutions below

0
seawave_23 On BEST ANSWER

Finally, I came to a solution! At first I found out that the json pipe gave me the right properties. Then I created a deadlineinput on my .ts file of type any and initialized it like this in the OnInit:

 this.deadlineinput = {
        formatted: ''
    };

here, one could also add the other options he wants to access (the json and on the html looks like this:

{ "day": "05", "month": "01", "year": "2017", "formatted": "05.01.2017", "momentObj": "2017-01-04T23:00:00.000Z" }

I put this on the .hmtl:

<ng2-datepicker [(ngModel)]="deadlineinput" [options]="datepickeroptions"></ng2-datepicker> <label> selected date is: {{deadlineinput.formatted}} </label>

I know that it shouldn't be like this, and I opened an Issue for the current version on github, but at least it's a workaround which helps me for now.

2
Bruno João On

You should use banana box notation instead to use only box:

[(ngModel)]="date"
  • (): from view to control data bind
  • []: from control to view data bind
  • [()]: 2 way data bind