Angular2: Date Format Textbox ngModel doesn't work

Still learning Angular2. Have a form where I have a startDate and endDate and I want to have input items for each. I am using two-way binding with my model object to a form.

<input type="date" name="EndDate" class="form-control input-sm" [(ngModel)]="selectedDeal.Enddate" required /> 

The date properties of my model are of type Date:

public EndDate: Date,

When I run this, and bind a model that has a valid date, it just shows mm/dd/yyyy in the text box. HTML5 type="date" support I presume. But it does not show the actual date. It has the date picker built in, which is excellent, but doesn't show the date that is already in the property.

If I change the type="date" to type="text", I see something like 2018-12-31T00:00:00, and lose my date support, plus this isn't user-friendly.

I'm trying to avoid: 1) Having to use the wrong data type (strings) and format my dates into strings for usage - this seems like a bad idea and practice 2) Using Javascript post form display to try to overwrite the value with string formatted date text

Is there an easier way to handle this?


You can achieve this by separating out the bindings, and doing a small amount of plumbing.

Template: (Note the date pipe is using the format 2016-12-31 , and the ngmodel and modelchange have been split)

<input type="date" name="EndDate" class="form-control input-sm" [ngModel]="selectedDeal.EndDate | date: 'y-MM-dd'" (ngModelChange)="dateChanged($event)" required />

Component:

private dateChanged(newDate) {
    this.selectedDeal.EndDate= new Date(newDate);
    console.log(this.selectedDeal.EndDate); // <-- for testing
  }
链接地址: http://www.djcxy.com/p/31092.html

上一篇: Angular2的devextreme datagrid中的数字格式

下一篇: Angular2:日期格式文本框ngModel不起作用