javascriptangulartypescriptcustom-data-attributedynamic-html

How to add data-autoload, data-origin and data-callback script tags in Angular typescript


I want to add my script in angular application which contains 'data-autoload, data-origin and data-callback' keys. I tried with _renderer2.createElement('script') method but it is throwing error.

Code

 let script = this._renderer2.createElement('script');
 script.type="application/javascript";
 script.data-autoload" =""
 script.data-origin" =""
 script.data-callback" =""

this._renderer2.appendChild(this.document.body,script)

Error

error ';' expected at

enter image description here

and same error for data-origin and data-callback

Kindly help me to resolve this issue


Solution

  • You have an invalid javascript variable.

    Rules for variable name:

    Reference link

    The code fix for this is to use setAttribute instead.

      constructor(private _renderer2: Renderer2) {}
      
      ngOnInit() {
        let script = this._renderer2.createElement('script');
        script.setAttribute('type', 'application/javascript');
        script.setAttribute('data-autoload', '');
        script.setAttribute('data-origin', '');
        script.setAttribute('data-callback', '');
        this._renderer2.appendChild(document.body,script)
      }
    

    Stackblitz Demo