角度2:如何将JavaScript Date对象与NgModel双向绑定一起使用 [英] Angular 2: How to use JavaScript Date Object with NgModel two way binding

查看:88
本文介绍了角度2:如何将JavaScript Date对象与NgModel双向绑定一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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>
...

其他数据(例如名字)会正确显示.但就我所得到的日期而言:

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.

我该怎么做?

推荐答案

更新:

StackBlitz

当我写下此答案时 DatePipe 不存在,现在您可以执行此操作

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


`


`

PLUNKER

您需要将date object转换为yyyy-mm-ddinput type="date"格式,这就是它的工作方式

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);
  }
}

这篇关于角度2:如何将JavaScript Date对象与NgModel双向绑定一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆