1

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?

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.