2

i have a jquery code which gets executed at ngAfterViewInit()

//myComponent.ts
ngAfterViewInit() {
    $(function () {
    $('#myElement').click(function (e) {
        //code working fine here
    });
}

but i want to move it to an external myScripts.js to simplify the component

i tried moving tthe code to an external file then use import but this makes the script to be called only once so if i navigate to a child component (which erases the html element myElement with the onclick defined ) then back to the parent myElement is back without the onclick event

so the question is :

what is the best practice to use jquery/javascript with angular4

1 Answer 1

1

You need to export your function from myScripts.ts and then import it and call it within ngAfterViewInit().

After exporting correctly you should be able to do:

// app.ts
import { myInitFunc } from './myScripts';

ngAfterViewInit() {
  myInitFunc();
}

// myScripts.ts
export function myInitFunc(): void {
  $(function () {
    $('#myElement').click(function (e) {
      //do stuff
    });
  }
};

Take a look at export: https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export

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

Comments

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.