简体   繁体   中英

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 ). 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. 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

(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]) .

Checkout this plunker to see the problem live (in 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. you have not imported formsModule in your module.

you can add change event.

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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