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?

0

1 Answer 1

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);
    );
Sign up to request clarification or add additional context in comments.

3 Comments

Questions like this has been already asked many times. Instead of answering them, please flag as a duplicate.
Anyways that is a correct answer, thanks!
@Valikhan Akhmedov can you have a little look at following question which is similar to this.stackoverflow.com/questions/44111238/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.