Angular 2 日期输入不绑定到日期值 [英] Angular 2 Date Input not binding to date value

查看:25
本文介绍了Angular 2 日期输入不绑定到日期值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图设置一个表单,但由于某种原因,我的 html 中的日期输入没有绑定到对象的日期值,尽管使用了 [(ngModel)]

trying to get a form set up but for some reason, the Date input in my html is not binding to the object's date value, despite using [(ngModel)]

html:

<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>

表单组件:

export class FormComponent {
    demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);  
}

用户类别:

export class User {
    constructor (
        public id: number,
        public email: string,
        public password: string,
        public firstName: string,
        public lastName: string,
        public date: Date,
        public gender: string,
        public weight: number,
        public dietRestrictions: string[],
        public fitnessGoals: string[]
    ){

    }
}

测试输出显示当前新"日期作为对象的值,但输入没有更新用户对象的日期值或反映该值,这表明双向绑定都不起作用.不胜感激.

A test output reveals the current "new" Date as the object's value, but the input doesn't update the User object's date value or reflect the value, suggesting neither of the two-way bindings are working. Help would be greatly appreciated.

推荐答案

你可以使用:

// view
<input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />

// controller
parseDate(dateString: string): Date {
    if (dateString) {
        return new Date(dateString);
    }
    return null;
}

您也可以选择不使用 parseDate 函数.在这种情况下,日期将保存为字符串格式,如2016-10-06"而不是日期类型(例如,我还没有尝试过在操作数据或保存到数据库时这是否会产生负面影响).

You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).

这篇关于Angular 2 日期输入不绑定到日期值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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