Angular2:从JavaScript函数调用组件方法 [英] Angular2: call component method from javascript function

查看:105
本文介绍了Angular2:从JavaScript函数调用组件方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在尝试在我的Angular2项目中使用jQuery来实现引导日期选择器.这是我到目前为止的内容:

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

在这里,我试图将ObservableService方法调用的路径传递到daterangepicker回调函数中,该函数在每次更改日期值时都会激活.所以,我得到了

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

错误.

如何调用Angular2组件,服务或js函数内部的任何方法?

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

推荐答案

在回调中使用箭头功能:

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

或使用Function的bind方法:

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

这篇关于Angular2:从JavaScript函数调用组件方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆