Home > database >  How to remove script tags in index.html from Angular Component
How to remove script tags in index.html from Angular Component

Time:10-17

<script data-jsd-embedded data-base-url="" data-key="" type="text/javascript" src="js-text-sample.js"></script>

Above is my sample script tag which is on index.html

I want to hide it inside an Angular component.

The angular component will fetch a config first from the API. Then it will validate if it needs to hide the script or not.

The script is a embedded widget that I need to hide if its false on the config API.

How do I hide it from the component code?

CodePudding user response:

You can do it the clasic, javascript way. When you get your response from the api, query the DOM to get a reference to the element and remove it:

const element = document.getElementById('widgetContainerId');
element.parentElement.removeChild(element);

This will remove the widget from the DOM.

If later during the lifecycle of the application you want to show it again, then you should not remove the whole element from the DOM, but hide it, maybe with display: none;:

const element = document.getElementById('widgetContainerId');
element.style.display = 'none';

Whenever you need it to be visible again, update the display property to something else, like block:

element.style.display = 'block';

CodePudding user response:

Instead of placing script tag and worrying about after logic to hide/show, why don't you create script tag at runtime based on result.

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.src='_SOURCE_HERE_'
        `;

        this._renderer2.appendChild(this._document.body, script);
    }
}
  • Related