Angular 2: How to use JavaScript Date Object with NgModel two way binding

后端 未结 7 1713
醉酒成梦
醉酒成梦 2020-12-02 10:01

I\'m working with Angular 2 and I have this code:

JS, this code initiates the employee-variable for the template:

handleEmployee(employee : Employee)         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 10:14

    I began trying to implement Ankit Singh's solution and ran in to a few problems with validation and timezone stuff. (Even after trying the suggestions in the comment section of that answer)

    Instead I chose to utilize moment.js to handle the transforming between string and date using ISO8601 format date strings. I've had great results in the past using moment.js so this was not a difficult decision. Seems to be working well for me, hopefully someone else finds this useful.

    For my Angular 2 app I ran npm install --save moment and then turned Ankit's solution into a wrapper around a js Date object:

    import * as moment from 'moment';
    
    export class NgDate {
    
        date: any;
    
        constructor() {
            this.date = new Date();
        }
    
        set dateInput(e) {
            if (e != "") {
                var momentDate = moment(e, moment.ISO_8601).toDate();
                this.date = momentDate;
            }
            else {
                this.date = null;
            }
        }
    
        get dateInput() {
            if(this.date == null)
            {
                return "";
            }
    
            var stringToReturn = moment(this.date).format().substring(0, 10);
            return stringToReturn;
        }
    }
    

    Then for the HTML:

    
    

提交回复
热议问题