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

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

    UPDATE:

    StackBlitz

    when I wrote this answer DatePipe did not exist, now you can just do this

    
    

    `


    Old Answer:

    PLUNKER

    You need to convert date object in the input type="date" format which is yyyy-mm-dd, this is how it will work

    Template:

    
    

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

提交回复
热议问题