微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular2:如何使用具有NgModel双向绑定的JavaScript 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);
  }
}

原文地址:https://www.jb51.cc/angularjs/144098.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐