Best practices for updating the DOM in Angular 7 without needing access to the original source code

I am faced with a situation where I need to manipulate the CSS classes of an element generated by a third-party library for which I do not have access to the source code.

While Angular typically recommends a specific method for adding and removing classes, that approach is not feasible in this scenario. Therefore, my question is: what is the best practice for achieving this task?

Consider the following hypothetical example on the DOM:

    <custom-control>
        <div class='one'>
        </div>
    </custom-control>

To address this issue, I have successfully implemented the following solution:

Firstly, I included ElementRef in the constructor of my component:

    private myElement: ElementRef

Then, I used querySelector to target the element and apply the desired class:

    const ele = this.myElement.nativeElement.querySelector('.one');
    ele.classList.add('two');

As a result, the output would be:

    <custom-control>
        <div class='one two'>
        </div>
    </custom-control>

Subsequently (based on certain conditions), I may need to remove the added class:

    ele.classList.remove('two');

NOTE: Given the constraints of not having access to the third-party code, how can this process be done in line with Angular's recommendations?

Answer №1

If you want to apply styles that penetrate component shadow boundaries, you can utilize the ::ng-deep selector in your CSS file.

::ng-deep <class-name> {
    <property>: <value>
}

For instance:

::ng-deep .one {
    color: blue;
}

To learn more about the usage of ::ng-deep, visit this link.

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

Is it possible to incorporate both ES5 and Typescript in a Node.js project simultaneously?

I have developed an Express app using ES5 notation, but now I need to implement interfaces. After realizing that there is no interface structure in ES5, I decided to write this part in TypeScript. However, I am facing an issue where I cannot require() thes ...

Struggling to retrieve the HTTP Response Code from an Angular Service

In my current project, I am utilizing Angular 4 for frontend development and Django REST Framework (DRF) as the backend. The issue I am facing is with extracting the Response JSON and HTTP Response Code separately from the DRF end in the form of a response ...

Escaping double quotes in dynamic string content in Javascript can prevent unexpected identifier errors

Need help with binding the login user's name from a portal to a JavaScript variable. The user's name sometimes contains either single or double quotes. I am facing an issue where my JavaScript code is unable to read strings with double quotes. ...

Empty array being returned by Mongoose after calling the populate() function

I've been struggling for the past 3-4 hours, banging my head against the wall and scouring countless articles here on StackOverflow, but I just can't seem to get my response to populate an array correctly. I'm working with Express.js, Typesc ...

No routes were found that match: ""

app.routes.ts import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { PushComponent } from './push/push.component'; const appRoutes: Routes = [ { path: ...

Error in Angular Apollo V3: Jest unable to locate module 'apollo-angular'

After recently updating angular apollo from version 2.6.0 to v3.0.0, my tests have been broken. I use jest for unit testing, and although the application compiles and runs without any issues, my tests cannot import any dependencies from 'apollo-angul ...

I am facing an issue with navigating between pages in Ionic 2. I am trying to move from one page to another, but it doesn't seem

My journey with Ionic 2 has just begun, and I'm excited to create a new page and navigate from the home page to the about page. However, when I attempted to use this.navCtrl.push('AboutPage'), an error message stating "push property does no ...

Can anyone help me troubleshoot createPortal in NextJS with TypeScript?

Currently, I am working on a toy project using Nextjs and Typescript. However, I have encountered an issue while attempting to create a Modal using createPortal. Whenever I click the button, nothing happens. Upon investigation, it seems that the value ...

Prevent accidental misuse of object[index] in Typescript

It caught me off guard when I discovered that TypeScript allows the following code: interface IFoo { bar: string; } const foo: IFoo = {bar: 'bar'}; console.log( foo['anything'] // I want TypeScript to stop this ); Is there a way ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

When deciding between StoreModule.forRoot and StoreModule.forFeature, consider the specific needs of your application

After researching, I discovered that the .forRoot function merges all reducers, allowing you to manipulate multiple reducers simultaneously when manipulating the state. On the other hand, the .forFeature function gives you the ability to manipulate each r ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

Remove focus from input field after submitting in a project using Typescript and React with react-hook-form

I'm currently working on a TS-React project and encountering an issue with barcode scanning in my inputs. I am using react-hook-form along with the useForm Hook. The form consists of one input-text field and a submit button, both within a global form. ...

Steps for preloading a user prior to the page loading

Main Concern I currently have an Auth Provider set up in my application that wraps around the entire _app.tsx file. This allows me to utilize the "useAuth" hook and access the user object from any part of the app. However, I am facing an issue when using ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Is it possible to incorporate regular React JSX with Material UI, or is it necessary to utilize TypeScript in this scenario?

I'm curious, does Material UI specifically require TypeScript or can we use React JSX code instead? I've been searching for an answer to this question without any luck, so I figured I'd ask here. ...

What is the rationale behind using :: before display: inline-block in Angular Material MDC's mat-mdc-form-field-error-wrapper, causing substantial padding?

I recently made the switch from Angular Material to Angular Material MDC in preparation for upgrading to Angular 17 from version 15. However, I've noticed that some styles are now broken. One issue I'm facing is a significant padding between the ...

There is an issue with the Hook call on the component list map in ReactJS

While working on Review components, I encountered an error when trying to use hooks. Here is the issue: I am using YhSection to manage my parallel components and utilizing array map to incorporate them in the layout content. Interestingly, if I use hoo ...

Can you clarify the significance of the "1" in this particular Typescript code snippet?

Can anyone provide some insight into the purpose of this '1' in the following TS code snippet? decryptPassPhrase() { this.$encrypt.setPrivateKey(privateKey); this.decryptedPassPhrase = this.$encrypt.decrypt(this.encryptedPassPhrase); ...

TypeScript versions 2.3 and 2.4 experiencing issues with generic overloads

After upgrading from typescript 2.2, I encountered an issue with the following example. interface ILayoutResult { id: string; data: any; } interface ILayout{ getResult<T extends ILayoutResult | ILayoutResult[] | void>() :T; } class te ...