Angular2: call component method from javascript function [duplicate]

限于喜欢 提交于 2020-01-05 02:37:01

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/41329505/angular2-call-component-method-from-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!