Angular2:如何使用带有NgModel双向绑定的JavaScript Date Object [英] Angular2: How to use JavaScript Date Object with NgModel two way binding
本文介绍了Angular2:如何使用带有NgModel双向绑定的JavaScript Date Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Angular 2,我有这个代码:
I'm working with Angular 2 and I have this code:
JS,此代码启动模板的employee-variable:
JS, this code initiates the employee-variable for the template:
handleEmployee(employee : Employee){
this.employee = employee;
this.employee.startDate = new Date('2005/01/01');
console.log(this.employee);
}
模板:
...
<div>
<label>Start date: </label>
<input [(ngModel)]="employee.startDate" type="date" name="startDate"/>
</div>
<div>
...
正确显示firstname等其他数据。但是我得到的日期是:
Other data like firstname is displayed correctly. But for the date I just get:
mm/dd/yyyy
在输入元素中,应该是日期。
In the input element, which should be a date.
我该怎么做?
推荐答案
更新:
当我将此答案写成 DatePipe 不存在,现在你可以这样做
UPDATE:
when I wrote this answer DatePipe did not exist, now you can just do this
<input [ngModel]="startDate | date:'yyyy-MM-dd'" (ngModelChange)="startDate = $event" type="date" name="startDate"/>
`
`
你需要转换日期对象
在输入type =date
格式, yyyy-mm- dd
,这就是它的工作原理
You need to convert date object
in the input type="date"
format which is yyyy-mm-dd
, this is how it will work
模板:
<input [(ngModel)]="humanDate" type="date" name="startDate"/>
组件(TS):
export class App {
startDate: any;
constructor() {
this.startDate = new Date(2005, 1, 4);
}
set humanDate(e){
e = e.split('-');
let d = new Date(Date.UTC(e[0], e[1]-1, e[2]));
this.startDate.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
}
get humanDate(){
return this.startDate.toISOString().substring(0, 10);
}
}
这篇关于Angular2:如何使用带有NgModel双向绑定的JavaScript Date Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文