Angular2:如何使用具有NgModel双向绑定的JavaScript Date对象
发布时间:2020-12-17 08:05:37 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 2,我有这个代码: JS,此代码启动模板的员工变量: handleEmployee(employee : Employee){ this.employee = employee; this.employee.startDate = new Date('2005/01/01'); console.log(this.employee); } 模板: ...div labelStart date
我正在使用Angular 2,我有这个代码:
JS,此代码启动模板的员工变量: 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显示正确。但是在我刚刚得到的日期: mm/dd/yyyy 在输入元素中,应该是一个日期。 我该怎么做?
更新:
当我写这个答案DatePipe不存在,现在你可以这样做 <input [ngModel]="startDate | date:'yyyy-MM-dd'" (ngModelChange)="startDate = $event" type="date" name="startDate"/> ` 老答案: PLUNKER 你需要转换日期对象的输入type =“date”格式是yyyy-mm-dd,这是怎么工作的 模板: <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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |