-1

I have components Home and About in Angular CLI app. I have included the javascript file required for both components in angular.json. But I want to add component-specific javascript files in the component. Say, I want to add home.js to the Home component. Is there any way possible?

I have tried adding script into DOM using this LINK, However, I want to add external js files instead.

Jaspal
  • 601
  • 2
  • 13
  • 23

1 Answers1

1

You can try

import * as test from 'test.js';

export class HomeComponent {
    ngOnInit() {
       test.testFunction(); //testFunction is in home.js
   }
}

// test.js
export function testFunction() {
    console.log('hello world');
}

Please refer to this answer: Angular 2: import external js file into component

Emon
  • 1,401
  • 14
  • 24
  • The file is loaded but functions inside home.js are unaccessible. – Jaspal Jun 29 '20 at 06:02
  • Did you export your function in home.js?@Jaspal – Emon Jun 29 '20 at 06:15
  • Can you provide some detailed info about your home.js. Or just create a simple `test.js` file with `testFunction` as I mentioned in the answer for testing the connection?@Jaspal – Emon Jun 29 '20 at 06:29
  • thanks, buddy it's working perfectly. I forgot to add the namespace test before calling function. – Jaspal Jun 29 '20 at 06:51