How to run an external js code in angular

Discussão em 'Angular' iniciado por user6781, Maio 4, 2025.

  1. user6781

    user6781 Guest

    Following this link I was able to load external js files as following:

    import { Component, OnInit, Renderer2 } from "@angular/core";
    import { ScriptService } from "@app/element-types/_services/script.service";

    const scriptPath = 'https://apis.google.com/js/api.js';
    declare let gapi: any;

    @Component({
    selector: 'app',
    templateUrl: './app.component.html',
    standalone: true
    })
    export class AppComponent implements OnInit {
    constructor(
    private renderer: Renderer2,
    private scriptService: ScriptService
    ) {}

    ngOnInit() {
    const scriptElement = this.scriptService.loadJsScript(this.renderer, scriptPath);
    scriptElement.onload = () => {
    console.log('Google API Script loaded');
    gapi.load('client', 'init');
    }
    }
    }


    And ScriptService.ts

    import {Inject, Injectable, Renderer2} from "@angular/core";
    import { DOCUMENT } from "@angular/common";

    @Injectable({
    providedIn: 'root'
    })

    export class ScriptService {
    constructor( @Inject(DOCUMENT) private document: Document) {}

    public loadJsScript(renderer: Renderer2, src: string): HTMLScriptElement {
    const script = renderer.createElement('script');
    script.type = 'text/javascript';
    script.src = src;
    renderer.appendChild(this.document.body, script);
    return script;
    }
    }



    So far so good, but I would like to change the code and instead of giving a url, I provide a script code and run it directly as follows:

    const scriptPath = 'https://apis.google.com/js/api.js';
    ---> change to
    const scriptPath = "alert('Hello world');";



    The error that I get now is:

    Uncaught SyntaxError: expected expression, got '<'


    So I want to know if it is possible, to do so.

    P.s. I don't want to define a js file in assets and then import it in the angular component and then call it.

    Continue reading...

Compartilhe esta Página