Bind an input with type datetime-local to a Date property in Angular 2

前端 未结 4 1282
太阳男子
太阳男子 2020-12-05 18:13

It is possible to bind a component property of Date type to a HTML5 input with type set to datetime-local?

In my component I have a poperty:

<         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 19:03

    I was looking into this problem as well and started to go down this examples road. However, you can use [(ngModel)] on an input of the type [date,datetime,datetime-local]. The key is to match the expected format the control is expecting. In this case it expects this format. Which also means the type that you bind to the control needs to be a string. I have provided an example plunker, that demonstrates how to use [(ngModel)].

    import { Component } from 'angular2/core';
    
    @Component({
      selector: 'my-app',
      template: `
          

    {{dateTimeLocal}}
    ` }) export class AppComponent { private _dateTimeLocal: Date; constructor() { this._dateTimeLocal = new Date(); } private parseDateToStringWithFormat(date: Date): string { let result: string; let dd = date.getDate().toString(); let mm = (date.getMonth() + 1).toString(); let hh = date.getHours().toString(); let min = date.getMinutes().toString(); dd = dd.length === 2 ? dd : "0" + dd; mm = mm.length === 2 ? mm : "0" + mm; hh = hh.length === 2 ? hh : "0" + hh; min = min.length === 2 ? min : "0" + min; result = [date.getFullYear(), '-', mm, '-', dd, 'T', hh, ':', min].join(''); return result; } public set dateTimeLocal(v: string) { let actualParsedDate = v ? new Date(v) : new Date(); let normalizedParsedDate = new Date(actualParsedDate.getTime() + (actualParsedDate.getTimezoneOffset() * 60000)); this._dateTimeLocal = normalizedParsedDate; } public get dateTimeLocal(): string { return this.parseDateToStringWithFormat(this._dateTimeLocal); } }

提交回复
热议问题