1

I have a problem with 2 way binding a time input. I can not find a way to accomplish this.

Here is an example in plnkr

http://plnkr.co/edit/Gyn8ER1LDBkkI0HieLZE?p=preview

And here is my code:

import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      Date: <input [(ngModel)] = "date"/>
      Time: <input type="time" [(valueAsDate)] = "date" />

    </div>
  `,
  directives: []
})
export class App {
  date = new Date();
  constructor() {
    this.name = 'Angular2'
  }
}
Kevin Kalitowski
  • 6,829
  • 4
  • 36
  • 52
Mohy Eldeen
  • 1,261
  • 2
  • 13
  • 24

2 Answers2

1

I see several way to do that:

  • Set the type to date in your input but it's not cross browser:

    <input type="date" .../>
    
  • Use an Angular2-compliant date picker like ng2-datepicker.

    <datepicker [(ngModel)]="test.date"></datepicker>
    

    See this question for more details:

  • Another way would be to implement a custom value accessor to parse / format the string of the input from / to a date object. Here is a way to do that:

    const DATE_VALUE_ACCESSOR = new Provider(
      NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => DateValueAccessor), multi: true});
    
    @Directive({
      selector: 'input[type=date]',
      host: { '(input)': 'doOnChange($event.target)' },
      providers: [ DATE_VALUE_ACCESSOR ]
    })
    export class DateValueAccessor extends DefaultValueAccessor {
      onChange = (_) => {};
      onTouched = () => {};
    
      writeValue(value:any):void {
        if (value!=null) {
          super.writeValue(value.toString());
        }
      }
    
      doOnChange(elt) {
        var val = elt.value;
        this.onChange(new Date(val));
      }
    }
    

    See this question for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • I ended up using the ngbootstrap time not date, but still this is not what I am looking for. I need to resolve the time input issue. – Mohy Eldeen Apr 22 '16 at 19:44
1

I would recommend a flexible visual time picker for angular 2+, you can install it easily using:

npm install amazing-time-picker --save

then, open your app.module.ts and add to your module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AmazingTimePickerModule } from 'amazing-time-picker'; // this line you need
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AmazingTimePickerModule // this line you need
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Please read api to understand how to use this module here:

https://github.com/owsolutions/amazing-time-picker

It would looks something like this:

Angular time picker, Angular 2 time picker, Clock picker

Alex
  • 715
  • 5
  • 14