0

I'm trying to call a JS function inside a component in my TS file, but I'm getting an exception.

Component

import '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new GanttMaster();
  }
}

Error:

Error referecences error: GanttMaster is not defined
Dino
  • 7,779
  • 12
  • 46
  • 85
Jindo vu
  • 11
  • 3

2 Answers2

3

You need to change the way you import the .js file:

import * as gantt from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new gantt.GanttMaster();
  }
}

If you want to use GanttMaster among several components, you can import the .js file in angular.json and declare a constant in app.module.ts like declare const GanttMaster: any. Then you can use it in your application.

Hope this helps.


UPDATE

Alternatively, you can import it the way you've already done, but declare the function manually before the import:

declare const GanttMaster: any;
import from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {

  constructor() {}

  ngOnInit() {
    var r = new GanttMaster();
  }
}

Ref: https://stackoverflow.com/a/37084553/1331040

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • actually, I try alreay but it not working, through error on webpackage like this: "TaskComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: _assets_js_gantt_ganttMaster_js__WEBPACK_IMPORTED_MODULE_18__.GanttMaster is not a constructor" – Jindo vu Sep 04 '19 at 08:30
  • Updated the answer. Can you try this one? – Harun Yilmaz Sep 04 '19 at 08:36
  • I'm try for your Update already, but it still got "ERROR ReferenceError: GanttMaster is not defined" – Jindo vu Sep 04 '19 at 08:48
0

In my project i load a js file from assets, something like this:

add this JavaScript file in scripts array in angular.json file like as above you have added jquery library.

"scripts": [
  .....
  "src/assets/js/custom.js"
]

custom.js:

function myTest() {
    alert('Welcome to custom js');
}

You need declare in your component

declare const myTest: any;
Miguel Pinto
  • 523
  • 2
  • 8