I have a script that I would like to run on one component only. I have managed to achieve adding the script on the component but a couple of things happen that I'm not entirely sure how to resolve.
- If I navigate to the component, the script is added to the DOM, but it isn't firing. If I refresh the page, it works
- If I navigate away to another component and return, the script is added again, and it can keep building up
component.ts
import { Component, OnInit } from '@angular/core';
import { Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-privacy',
templateUrl: './privacy.component.html',
styles: []
})
export class PrivacyComponent implements OnInit {
constructor(private _renderer2: Renderer2, @Inject(DOCUMENT) private _document) {
let s = this._renderer2.createElement('script');
s.type = `text/javascript`;
s.src = `../../assets/scripts/privacy.js`;
this._renderer2.appendChild(this._document.body, s);
}
ngOnInit() {
}
}
.remove()in Destroy lifecycle hook. ill create an example for you.this._renderer2.removeChild(this._document.body, s)