2

Currently I'm trying to implement bootstrap datepicker, which using jQuery, with my Angular2 project. Here is what I have so far:

import {Component, AfterViewInit, Injector, Inject} from '@angular/core';
import {ObservableService} from "../../../services/data-observable.service";
declare var $:any;

@Component({
    selector: 'date-range',
    moduleId: module.id,
    template: `<input name="daterange" class="filter-date-range"/>`
})

export class DateRange implements AfterViewInit {

    options = { locale: {
        format: 'YYYY-MM-DD'
    },
        startDate: '2013-01-01',
        endDate: '2013-12-31'};

    constructor(@Inject(Injector) private injector: Injector,
                @Inject(ObservableService) private _observable: ObservableService) { }

    ngAfterViewInit() {
        $('input[name="daterange"]').daterangepicker(
            this.options,
            function (start, end) {
                let obj = {};
                obj['start'] = start;
                obj['end'] = end;

                this._observable.updateFilter(obj);
            }
        );
    }
}

Everything works perfect, except this piece of code

this._observable.updateFilter(obj);

Here I'm trying to path ObservableService method call into daterangepicker callback function, which activates each time date value changed. So, I'm getting a

Uncaught TypeError: Cannot read property 'updateFilter' of undefined

error.

How can I call a method of Angular2 component, service or whatever inside js function?

Majesty
  • 2,097
  • 5
  • 24
  • 55

1 Answers1

3

Use arrow function in callback:

     $('input[name="daterange"]').daterangepicker(
        this.options,
        (start, end) => {
            let obj = {};
            obj['start'] = start;
            obj['end'] = end;

            this._observable.updateFilter(obj);
        }
    );

Or use bind method of Function:

     $('input[name="daterange"]').daterangepicker(
        this.options,
        function (start, end) {
            let obj = {};
            obj['start'] = start;
            obj['end'] = end;

            this._observable.updateFilter(obj);
        }.bind(this);
    );
Valikhan Akhmedov
  • 961
  • 1
  • 10
  • 14
  • Questions like this has been already asked many times. Instead of answering them, please flag as a duplicate. – Michał Perłakowski Dec 26 '16 at 10:10
  • Anyways that is a correct answer, thanks! – Majesty Dec 26 '16 at 10:12
  • @Valikhan Akhmedov can you have a little look at following question which is similar to this.http://stackoverflow.com/questions/44111238/calling-a-method-in-the-component-from-a-javascript-angular2 – vigamage May 22 '17 at 11:36