javascriptangularangular-cli-v9

How can I add external JS file in Angular CLI component, specific to the component only?


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.


Solution

  • 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