Helen Reeves
Helen Reeves

Reputation: 469

Unable to call javascript function from Typescript in Angular 6

The javascript function (help) below is not being called from ngOnInit()?

In web console: ERROR ReferenceError: "help is not defined"

Would you know how this can be done?


src/assets/myjs.js:

function help() {
    console.log("hilfe");   
}

src/app/highlight.directive.ts:

import { Directive, ElementRef, OnInit } from '@angular/core';

declare function help() : any;

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {

  constructor(el: ElementRef) { 
    el.nativeElement.style.backgroundColor = 'yellow';
  }

  ngOnInit() {
    help();
  }

}

angular.json:

...

    "styles": [
         "src/styles.css"
    ],
    "scripts": [
        "src/assets/myjs.js"
    ],
},
...

Upvotes: 1

Views: 17350

Answers (4)

Boobalan
Boobalan

Reputation: 855

ES6/TS

Simply export your function Help in help.ts

export default function Help(){}

Import anywhere by

import Help from 'help'

Upvotes: 2

Harry Whitehouse
Harry Whitehouse

Reputation: 41

There are two sections in the angular.json file for scripts. One is "architect:" the other is "test:". Is your scripts definition in both places?

    "scripts": [ "src/assets/myjs.js" ],

And I doubt this second point would make a difference, but I was guided by one post to create a sub-directory under assets called "js". Like this...

    "scripts": [ "src/assets/js/myjs.js" ],

You also might try an alert('hilfe') in your js function rather than a console.log()... although either should work.

Your setup seems pretty correct otherwise.

In additional to that you need to declare the same function in your component file. For example the function name is JavaScript file is help(), you need to declare it just above the component like: declare function help(): any; and then call the help function where you want to call in that file.

Upvotes: 1

Damir Beylkhanov
Damir Beylkhanov

Reputation: 545

@simon-reeves

"scripts": [ "src/assets/myjs.js" ],

I had to put testjs.js file into assets folder and applied path like below

moreover, make sure that assets section is defined an above and that file is exists by this path in sources

enter image description here

In addition, check content of the generated scripts.js file , cuz, it should contains your help function, e.g. in my case it's myalert function

enter image description here

hope it should help you

Upvotes: 1

erdemgunenc
erdemgunenc

Reputation: 997

What about exporting your function like

module.exports.help = () => {
      console.log("hilfe");   
}

Then

const helper = require("./pathofyourfile");

Upvotes: 2

Related Questions