0

I have one custom query function written in a javascript file under the source folder (i.e. /src/assets/inlineedit.js) of Angular application.

Here's the content of the file.

$.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();
        });
    });
};

Now, I want to call this function within Angular mycomponent.ts file and content looks as below:

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

But, I'm getting error like

Property 'inlineEdit' does not exist on type 'JQuery'

How to call jQuery functions inside Angular components?

1 Answer 1

1

You could use <any> type-casting like this:

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

Or even better:

First install @types/jquery from npm

npm install @types/jquery --save-dev

Then add a local typings file and declare your plugin function in it

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

Then you can use your plugin.

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

Sign up to request clarification or add additional context in comments.

6 Comments

It is showing ERROR TypeError: $(...).inlineEdit is not a function
Did you import your inlineedit.js file in the scripts section of the angular.json file? And did you install jquery and imported it too?
Yeah, I did all of that. But still facing the same issue. Where do I create typings.d.ts file?
You create a file (you can give any name) in a desired path and import it in tsconfig.json file in src location. Check this thread out: stackoverflow.com/questions/51876748/…
You can add much parameter as you want in the declaration. interface JQuery { inlineEdit(replaceWith: any, connectWith: any): any; }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.