Adding script tags in Angular component template
Maybe a little late to the party here, but since the above answers do not work well with Angular SSR (e.g. document is not defined
server-side or document.createElement is not a function
), I decided to write a version that works for Angular 4+, in both server and browser context:
Component Implementation
import { Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
class MyComponent implements OnInit {
constructor(
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document: Document
) { }
public ngOnInit() {
let script = this._renderer2.createElement('script');
script.type = `application/ld+json`;
script.text = `
{
"@context": "https://schema.org"
/* your schema.org microdata goes here */
}
`;
this._renderer2.appendChild(this._document.body, script);
}
}
Service ImplementationNOTE: Services cannot use Renderer2
directly. In fact, rendering an element is supposed to be done by a Component. However, you might find yourself in situation where you want to automate the creation of JSON-LD script
tags on a page. As an example, a situation could be to invoke such function on route navigation change events. Hence I decided to add a version that works in a Service
context.
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
/**
* Use a Service to automate creation of JSON-LD Microdata.
*/
class MyService {
constructor(
@Inject(DOCUMENT) private _document: Document
) { }
/**
* Set JSON-LD Microdata on the Document Body.
*
* @param renderer2 The Angular Renderer
* @param data The data for the JSON-LD script
* @returns Void
*/
public setJsonLd(renderer2: Renderer2, data: any): void {
let script = renderer2.createElement('script');
script.type = 'application/ld+json';
script.text = `${JSON.stringify(data)}`;
renderer2.appendChild(this._document.body, script);
}
}
How to embed a script tag into Angular component
Don't insert the script tag manually. Import the library in your angular.json
, in scripts
section:
"scripts": [
"./node_modules/yourtablelibrary/build/yourtablelibrary.min.js"
]
Reference: https://medium.com/@clintpitzak/how-to-use-external-javascript-libraries-in-angular-8-247baacbdccf Insert script tag into Angular 4 HTML Component
Your component has an element with id editor
. This will only be available in the ngAfterViewInit
hook of the component. Once this is called, the window.onload
has been called ages ago. Also when the onload
is called, the element doesn't exist at all yet, so it's also a bad idea to put it there.
Best would be to call the method from inside the ngAfterViewInit
of your component, and use the @ViewChild
annotation:
declare const PhotoEditorSDK: any;
@Component({
template: `<div style="width: 100vw; height: 100vh;" #editor></div>`
})
export class EditorComponent implements AfterViewInit {
@ViewChild('editor') editor: ElementRef<HTMLElement>;
ngAfterViewInit(): void {
const image = new Image();
image.addEventListener('load', () => {
const editor = new PhotoEditorSDK.UI.DesktopUI({
container: this.editor.nativeElement,
license: '{"owner":"Imgly Inc.","version":"2.1", ...}',
editor: {
image
},
assets: {
baseUrl: '/assets'
}
});
});
image.src = './example.jpg'
}
}
Angular blocks script tags in template
To input HTML in some component you must to use DomSanitizer, like this:
data:SafeHtml;
constructor(private sanitizer: DomSanitizer) { ... }
yourFunction() {
this.data = this.sanitizer.bypassSecurityTrustHtml(YOUR_STRING_HTML)
}
In component it's right.<div [innerHTML]="data"></div>
Where to place the script tag in a Angular App
Try having a look at the Angular documentation for adding libraries that can't be imported into an app in the usual way. In short: You don't have to add script-tags to the index.html manually. Instead, you can install the npm package and add the script to your angular.json. There, you will find an array called "scripts" where you can link the script that was downloaded into node_modules:
"scripts": [
// just an example:
"node_modules/jquery/dist/jquery.slim.js",
// place the path to your script here
],
Related Topics
JavaScript String Array to Object
Why Are Exceptions Used for Rejecting Promises in Js
Unchecked Runtime.Lasterror While Running Tabs.Executescript
React Routing Works in Local MAChine But Not Heroku
Gmail Extension, Sendmessage to Background from Page Context
How to Initialize a JavaScript Date to Midnight
How to Convert Numbers Between Different Bases in JavaScript
Do Websockets Allow for P2P (Browser to Browser) Communication
D3.JSON Method Doesn't Return My Data Array
How to Trigger Click on Page Load
How to Send Images to Node Js with Axios