Sometimes we want to insert script tag in angular app, For an instance we have third party APIs or widget and we wanted to add it in our page then in this condition provided script are not angular friendly or we can say it can be pure JavaScript. so to insert this type of script we need to load it dynamically in our Dom.
In angular we can add those script in two ways first one is using the pure javascript way and other in angular way which also work on server application.
Let’s discuss the both way to Insert script tag dynamically in html in angular
Load script tag url using pure javascript in component
In this way we will create a component and then load the script in Dom so it can work as expected as below
loadScriptByUrl(url, afterload) {
let dynamicScript = document.createElement('script');
dynamicScript.type = 'text/javascript';
dynamicScript.async = true;
dynamicScript.src = url;
dynamicScript.id = 'dynamic_' + this.count;
document.body.appendChild(dynamicScript);
this.count++;
dynamicScript.addEventListener('load', () => {
afterload(dynamicScript, dynamicScript.id);
});
}
Load script tag text using pure javascript in component
In this way we will create a component and then load the script in Dom so it can work as expected as below
loadScriptByUrl() {
let dynamicScript = document.createElement("script");
dynamicScript.type = "text/javascript";
dynamicScript.async = true;
dynamicScript.text = "alert('this is inserted dynamically')";
document.body.appendChild(dynamicScript);
}
Understand it with an example
Step 1 : Create an angular app
First step is to setup an angular app using below command
ng new example-component
Step 2: Create a Component
Create a component so we can use insert the script tag in it dynamically.
ng g c test-script
import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-test-script',
templateUrl: './test-script.component.html',
styleUrls: ['./test-script.component.css']
})
export class TestScriptComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Step 3 : Add loadScriptUrl method to component
Now add the logic for adding script tag in component in JavaScript way
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test-script',
templateUrl: './test-script.component.html',
styleUrls: ['./test-script.component.css'],
})
export class TestScriptComponent implements OnInit {
count = 0;
constructor() {}
ngOnInit() {
this.loadScriptByUrl(
'https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js',
function (scriptref, id) {
var cleave = new window['Cleave']('.input-phone', {
creditCard: true,
onCreditCardTypeChanged: function (type) {
// update UI ...
},
});
// do your work after load
}
);
}
loadScriptByUrl(url, afterload) {
let dynamicScript = document.createElement('script');
dynamicScript.type = 'text/javascript';
dynamicScript.async = true;
dynamicScript.src = url;
dynamicScript.id = 'dynamic_' + this.count;
document.body.appendChild(dynamicScript);
this.count++;
dynamicScript.addEventListener('load', () => {
afterload(dynamicScript, dynamicScript.id);
});
}
}
Or in Angular server side rendering
import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnInit, Renderer2 } from '@angular/core';
@Component({
selector: 'app-test-script',
templateUrl: './test-script.component.html',
styleUrls: ['./test-script.component.css'],
})
export class TestScriptComponent implements OnInit {
count = 0;
constructor(
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document: Document
) {}
ngOnInit() {
this.loadScriptByAngularWay(
'alert("Dynamic loaded SSR")',
function (scriptref, id) {
// do your work after load
}
);
}
public loadScriptByAngularWay(text,afterload) {
let script = this._renderer2.createElement('script');
script.type = `text/javascript`;
script.text = text;
this._renderer2.appendChild(this._document.body, script);
script.addEventListener('load', () => {
afterload(script);
});
}
}
Here we added both way using loadScriptByAngularWay
and loadScriptByUrl
method, also we added callback so we can only run the external script method after load.
we added a library to format input field https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js
Step 4 : Add html in template
Add simple html in template so we can test our implementation
<p>
test-script works!
<input class="input-phone" type="text" />
</p>
Live code