Angular 2时间输入双向绑定

时间:2016-04-22 16:51:22

标签: angular

我遇到了2路绑定时间输入的问题。我无法找到实现这一目标的方法。

这是plnkr

中的一个例子

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

这是我的代码:

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'
  }
}

2 个答案:

答案 0 :(得分:1)

我看到了几种方法:

  • 在输入中将type设置为date,但它不是跨浏览器:

    <input type="date" .../>
    
  • 使用符合Angular2标准的日期选择器,例如ng2-datepicker。

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

    有关详细信息,请参阅此问题:

  • 另一种方法是实现一个自定义值访问器来解析/格式化日期对象的输入字符串。这是一种方法:

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

    有关详细信息,请参阅此问题:

答案 1 :(得分:1)

我建议灵活的角度2+视觉时间选择器,您可以使用以下方法轻松安装:

npm install amazing-time-picker --save

然后,打开您的app.module.ts并添加到您的模块:

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 { }

请阅读api以了解如何在此处使用此模块:

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

它看起来像这样:

Angular time picker, Angular 2 time picker, Clock picker

相关问题