Dunowen
Dunowen

Reputation: 137

Set specific time in <input type="date"> with Angular

I would like to set a specific Date programatically for my control with Angular2, but no matter how I try it, the input always displays "yyyy. mm. dd." in my browser.

Here's my code: HTML:

<input class="form-control" type="date" [(ngModel)]="dateFrom" name="dateFrom" min="2016-10-01" [value]="2016-10-01" />

Typescript

public dateFrom: Date;  
constructor() {
}
ngOnInit() {
    this.dateFrom = new Date(Date.parse("2016-10-01"));
}

Please note that min="date" and [value]="date" also didn't work in pure HTML code. Is there something I'm missing or it is a really bad idea, to set an input's value from code?

Upvotes: 1

Views: 7278

Answers (2)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37373

this gonna work, see it in action here plunker

use date pipe, (ngModelChange) and [ngModel]:

  <input class="form-control" type="date" [ngModel] ="dateFrom | date:'yyyy-MM-dd'" (ngModelChange)="$event = dateFrom" name="dateFrom" min="2016-10-01" [value]="2016-10-01" />

Upvotes: 0

Eddie Martinez
Eddie Martinez

Reputation: 13910

If you need the value to be initialized from an Angular2 variable the input has to part of Angular2 form component, a model-driven form or template driven form. And the date input is expecting a string representation of a date, not the javascript date object

value = date # A string representing a date.

documentation

Change your code to use string like this:

TypeScript Component

public dateFrom: string =  "2016-10-01";

Html Component

<form #form="ngForm">
  <input type="date"  [(ngModel)]="dateFrom" name="dateFrom"/>
</form>

Upvotes: 2

Related Questions