在Angular Component类中调用自定义jQuery函数

时间:2019-06-10 09:17:02

标签: javascript jquery angular function

我在Angular应用程序的源文件夹(即/src/assets/inlineedit.js)下的javascript文件中编写了一个自定义查询功能。

这是文件的内容。

$.fn.inlineEdit = function(replaceWith, connectWith) {
    $(this).hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });

    $(this).click(function() {
        var elem = $(this);
        elem.hide();
        elem.after(replaceWith);
        replaceWith.focus();
        replaceWith.blur(function() {
            if ($(this).val() != "") {
                connectWith.val($(this).val()).change();
                elem.text($(this).val());
            }
            $(this).remove();
            elem.show();
        });
    });
};

现在,我想在Angular mycomponent.ts文件中调用此函数,其内容如下:

import { Component, ViewChild, ElementRef  } from '@angular/core';
@Component({
  selector: 'app-pivotgrid',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.css']
})
export class mycomponent {
    OnCellclick (event): void
    {
       var replaceWith = $('<input name="temp" type="text" />'),
            connectWith = $('input[name="hiddenField"]');

        $('#innerDiv').inlineEdit(replaceWith, connectWith);
    } 
}

但是,我遇到了

这样的错误
  

类型'JQuery'不存在属性'inlineEdit'

如何在Angular组件中调用jQuery函数?

1 个答案:

答案 0 :(得分:1)

您可以像这样使用<any>类型转换:

(<any>$('#innerDiv')).inlineEdit(replaceWith, connectWith);

甚至更好:

首先从@types/jquery安装npm

npm install @types/jquery --save-dev

然后添加本地类型文件并在其中声明您的插件功能

interface JQuery {
  <your-plugin-name>(options?: any): any;
}

然后您就可以使用插件了。

来源:https://medium.com/all-is-web/angular-5-using-jquery-plugins-5edf4e642969

相关问题