codyj110
codyj110

Reputation: 73

Angular setting default value of HTML datepicker

The [(ngModel)] is not setting default value for date picker. I have tried various different ways to populate the date picker but have been unable to.

My HTML

<input id="START_DATE" type="datetime-local" [(ngModel)]="startDate"/>

In that example the binding works but I am unable to set the default value.

I can set the value if i just interpolate the value but then i lose my 2 way binding. value="{{startDate}}"

Upvotes: 7

Views: 22463

Answers (3)

Pedro Su&#225;rez
Pedro Su&#225;rez

Reputation: 41

I cannot comments that last answer by my reputation. It is low and I don't know why stackoverflow don't let me upgrade it. That last one works for me and better because I needed only date and I used

startDate = new Date().toISOString().slice(0, 10)

Upvotes: 1

gagan
gagan

Reputation: 269

You can bind a string type property to the input date type. You have to convert the "Date object" to a "string" and store the string value in a class component property. Bind the respective property (component class) to the HTML element (template).

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  startDate = new Date().toISOString().slice(0, 16);

  constructor(){
  }
}

You can also create a customizable "date to string" format function as per the use-case.

Upvotes: 5

Younis Ar M
Younis Ar M

Reputation: 941

Plunker - https://plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">

Upvotes: 10

Related Questions