Removing script tags from the index.html file in an Angular Component can be done by manipulating the

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

This is a sample script tag located in index.html.

I am looking to conceal it within an Angular component.

The Angular component will initially retrieve a configuration from the API. It will then determine whether or not to conceal the script based on this configuration.

The script functions as an embedded widget that should be hidden if the corresponding value is false in the configuration retrieved from the API.

Is there a way to hide it directly from the component code?

Answer №1

Why bother with inserting a script tag and dealing with logic to show/hide it later on? Instead, consider generating the script tag dynamically based on the result.

import { Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

class CustomComponent implements OnInit {

    constructor(
        private _renderer2: Renderer2, 
        @Inject(DOCUMENT) private _document: Document
    ) { }

    public ngOnInit() {
        
        let dynamicScript = this._renderer2.createElement('script');
        dynamicScript.src='_SOURCE_HERE_'
        `;

        this._renderer2.appendChild(this._document.body, dynamicScript);
    }
}

Answer №2

If you want to achieve this in a classic JavaScript way, you can do so by fetching the response from the API and then targeting the specific element in the DOM to remove it:

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

This action will effectively eliminate the widget from the DOM.

In case you need to display the widget again at some point during the application's lifecycle, it is advisable not to completely remove the element from the DOM but rather hide it using display: none;:

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

To make the widget visible again when required, simply change the display property to something else such as block:

showElement.style.display = 'block';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Strategies for obtaining multiple instances of duplicated data within an array object

this array contains multiple instances of duplicate data var = [{id: 1, name:'jeff'}{id:1, name:'kent'}{id:2, name:'ynez'}{id:2, name:'cloe'}{id:3, name:'Ron'}{id:3, name:'chester'}] to achieve ...

Issue with Angular build process

Upon running 'npm run dist' to build the ES2015 javascript bundles, I encountered an error (Exhibit 1) while no error occurred when using 'npm start -o'. The issue appears to be related to the Angular Material Autocomplete component (Ex ...

Angular 11 - How $rootScope Behaves When Navigating in a Hybrid AngularJS Environment

I have been in the process of transitioning a sizable AngularJS application to Angular 11. Thus far, I have successfully reworked the sign-in and sign-up pages in Angular 11. Post authentication, the AngularJS app is lazily loaded as shown below: const rou ...

@nestjs - JwtModule.registerAsync is failing to register in a timely manner, resulting in unresolved dependencies

Encountering some challenges with the registerAsync function in combination with JwtModule and JwtService. While browsing various discussions, it seems like many were stuck on ConfigModule, but that's not a part of my project. Let me provide some con ...

Issue experienced with Nebular's NbRoleProvider when running in a live environment

Here is my role.provider.ts: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { map } from 'rxjs/operators/map'; import { NbAuthService, NbAuthJWTToken } from '@nebular/aut ...

What is the method to incorporate type hints for my unique global Vue directives?

When I import or create a directive in an SFC file, I can receive TypeScript hints like this: import vFocus from 'my-custom-component-library'; View demo with ts hints However, if I globally register it in main.ts, the type hints are not availa ...

Do we require two-way binding to effectively exchange data between components in this situation?

I'm currently facing some challenges in updating data in a child component when new data is added from the parent component. Here's a snippet of my template: <ion-content> <app-feed-comments [comments]="comments" [userId]=& ...

Ways to enhance this directive for displaying a unique error message using mat-error

When using AngularMaterial form components, I need to show an error message when the form control is in an invalid state. This message should be recalculated every time the status or value of the form control changes. I will provide the form control and er ...

What steps should I take to create a TypeScript generic class that is limited to only accepting types that are arrays of objects?

I'm working on creating a sample of a generic class in TypeScript. My goal is to have a generic class named RecordsProcessor that is limited to only accept types that are arrays of objects. If I try to pass a number to the constructor, TypeScript cor ...

Performing a task once elements are added to an array

I created a function that calls an API to retrieve information for each product and then stores it in an array. After looping through all the products, I want to perform an action with the array. Here is my code: newProducts: any = [] loadOfferRelated(o ...

This browser does not recognize the tag <>. To render a React component, ensure its name starts with an uppercase letter

MyIcons.tsx export const ICONCAR = () => ( <span className="svg-icon svg-icon-primary svg-icon-2x"><svg xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="24px" height=&qu ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

Unable to load the .js file within the Angular module

I am facing an issue with my Angular sidebar component that is trying to load a local script called sidebar.js. I have the following code in src\app\sidebar\sidebar.component.ts: ngAfterViewInit(): void { const s = document.createEleme ...

Using an array of objects as a data source for the Material Angular table

My user data is causing some issues and looks like this... [{"firstName":"Pinkie","lastName":"Connelly","username":"Darlene.Marvin","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19506a767b7c75464b7c77777c6b5971766d74 ...

Can we ensure type safety for the options of method decorators?

Exploring the creation of utility decorators like memoize and rateLimiter, I aim to maximize type safety while minimizing unnecessary boilerplate code. Can decorators maintain full type safety without explicitly defining generics? type GET_FUNCTION_SIGNA ...

Unusual problem with [(ngModel)] not updating after Apollo subscription

I've encountered a strange issue with [(ngModel)] while working on an Angular 5 project. I have set up a form with inputs that successfully connect to the database using Apollo for sending GraphQL queries and mutations. The issue arises in editing set ...

What is the process for setting up a server-side Meteor Collection without the necessity of direct interaction?

I'm just starting out with Meteor and working on a basic recipe list. In my file (/imports/api/recipes.ts), I have defined my Recipe collection: // imports/api/recipes.ts export interface Recipe { _id?: string; title: string; createdAt: Date; } ...

Specify the second parameter as a generic class that corresponds to the first parameter of the function

Given the example below, the second parameter of the fn function requires a class with a static attribute controle and an instance attribute controle, both of type number. interface Base { controle: number new(...args: any[]): { controle: n ...

Should a separate module be created for each component, or should there be a single module for all shared

In my development approach, I utilize ionic pages that consist of various shared components. I am contemplating whether it would be best to have a unified module for all the components in the "shared" folder or if each component should have its own modul ...

Firebase Error: Page Not Found

I recently set up an Angular2 application and added Firebase using npm. I successfully imported it into my app.component.ts without any errors showing up in my text editor. The package.json file also indicates that Firebase is installed correctly. However ...