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

后端 未结 7 1717
醉酒成梦
醉酒成梦 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:10

    I think the accepted answer lacks a function call to transform input date string to Date object. So this:

    (ngModelChange)="startDate = $event"
    

    Should be something like:

    (ngModelChange)="startDate = toDate($event)"
    

    I'm using Moment.js, which makes things MUCH easier:

    my.component.ts

    ...
    import * as moment from 'moment';
    ...
    @Component ({
      ...
    })
    export class MyComponent implements OnInit {
    
      public fromDate: moment.Moment;
      public toDate: moment.Moment;
      
      ngOnInit() {
        this.toDate = moment();
        this.fromDate = moment().subtract(1, 'week');
      }
    
      dateStringToMoment(dateString: string): moment.Moment {
        return moment(dateString);
      }

    my-component.html

    ...
    
    
    ...

提交回复
热议问题