简体   繁体   English

如何将日期选择器中的值绑定到angular2模型?

[英]How can I bind a value from a datepicker to an angular2 model?

I develop an app with angular2 and have to use a datepicker for firefox ( other browsers have in inbrowser datepicker ). 我用angular2开发了一个应用程序,并且必须为firefox使用datepicker( 其他浏览器在inbrowser datepicker中具有 )。 The problem is by using a datepicker I loose the two way binding of my model. 问题是通过使用日期选择器,我松开了模型的双向绑定。 It doesn't matter if I use pikaday , jquery ui or other javascript datepickers. 我是否使用pikadayjquery ui或其他javascript datepickers都没有关系。 The behaviour is the same. 行为是相同的。

<input 
    type="date" 
    name="datum" 
    class="datepicker" 
    [(ngModel)]="datum" 
/>

Other way, same result 其他方式,相同结果

<input 
    type="date" 
    name="datum" 
    class="datepicker" 
    [value]="datum" 
    (input)="datum = $event.target.value" 
/>

jQuery UI datepicker fallback for firefox Firefox的jQuery UI datepicker后备

(function() {
    var elem = document.createElement('input');
    elem.setAttribute('type', 'date');

    if ( elem.type === 'text' ) {
        $('.datepicker').datepicker(); 
    }
})();

If I pick a date it only appears in the input field, but doesn't exists as value in the model (btw, I tried a plunker but it failed because of the 'banana in a box' syntax [I can't bring jQuery to work in it]) . 如果我选择一个日期,则它仅出现在输入字段中,但不作为模型中的值存在 (顺便说一句, 我尝试了一个插销,但由于“香蕉在盒子里”的语法而失败了[我无法带上jQuery在其中工作])

Checkout this plunker to see the problem live (in firefox). 查看此插件 ,查看问题的现场直播(在Firefox中)。

I know, this is a very specific problem, but maybe someone had it before and found a solution. 我知道,这是一个非常具体的问题,但也许有人以前曾遇到过,并找到了解决方案。 And if this one can post it here this would make me very happy. 如果这个人可以张贴在这里,这会让我非常高兴。

This works for me...ngModel is binding properly. 这对我有用... ngModel正确绑定。 you have not imported formsModule in your module. 您尚未在模块中导入FormsModule。

you can add change event. 您可以添加更改事件。

<input 
    type="date" 
    name="datum" 
    class="datepicker" 
    [ngModel]="datum" 
    (ngModelChange)="onChange($event)" 
/>


onChange(event : any){
  // add your code here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM