How to detect bootstrap datetimepicker change events within angular2

后端 未结 5 1132
感情败类
感情败类 2020-12-05 08:14

I am using the bootstrap datetimepicker in angular 2

https://eonasdan.github.io/bootstrap-datetimepicker/

In my template i have:

5条回答
  •  無奈伤痛
    2020-12-05 08:35

    The problem as stated by the other answers is that ngModel is not picking up the change being made by the third-party library. ngModel uses two-way data-binding. Essentially, when you say

    that is equivalent to

    .

    What I did was create a directive to emit the ngModelChange event, as follows:

    @Directive({
        selector: [datepicker],
        outputs: [
            "ngModelChange"
        ]
    })
    export class DatePickerDirective {
        //Emits changes to ngModel
        ngModelChange = new EventEmitter();
        el: JQuery;
    
        //Obtains the handle to the jQuery element
        constructor(el){
            this.el = jQuery(el.nativeElement);
        }
    
        ngOnInit() {
            this.el.datetimepicker({
                //Initialization options
            });
    
            this.el.on('dp.change', (event) => {
                var moment: Moment = event.date;
    
                //Emit new value
                this.ngModelChange.emit(date.format(/*However you want it formatted*/));
            });
        };
    
        ngOnDestroy() {
            //Clean up
            this.el.data('DateTimePicker').destroy();
        };
    };
    

提交回复
热议问题