Discovering the best method for accessing CSS classes locally within an Angular component

In order to style a 3rd-party component with custom styles, I need to access the dynamically generated css classname from within an angular component.

Angular applies transformations to local css classnames for scoping purposes. However, when trying to style an ngx-datatable component with custom classnames, they no longer match due to Angular's modifications.

While adding classnames to the global scope or using ::ng-deep are solutions, I prefer not to compromise encapsulation.

dashboard-component.ts

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent {
    getRowClass(row){
        return 'my-class';
    }
}

dashboard-component.scss

.my-class {
   background: green;
}

dashboard-component.html

<ngx-datatable
   [rowclass]="getRowClass"
></ngx-datatable>

I believe that accessing a reference to the css class within the component, like this._styles, which would hold the runtime-generated class name, would allow me to implement:

getRowClass(row){
    return this._styles['my-class'];
}

Answer №1

It seems like you are facing challenges in applying your styles to the ngx-datatable.

One approach is to utilize

encapsulation: ViewEncapsulation.None
within your @component, but exercise caution as it may result in unexpected css behaviors.

Another option is to create a dedicated container for your dashboard.html file:

<div class="dashboard-container">
  <ngx-datatable></ngx-datatable>
</div>

Then, in your dashboard.scss, you can style elements by referencing the parent container:

.dashboard-container {
  .my-style{}
}

Answer №2

If you want to avoid using ::ng-deep, it's recommended to include the CSS classes for ngx-datatable in the global style file.

For an example, you can refer to the ngx-datatable demo in the asset/app.css where they followed the same approach.

Alternatively, you can set

encapsulation: ViewEncapsulation.None
on the component to ensure that the class name remains the same.

@Component({
  selector: "app-demo",
  templateUrl: "./demo.component.html",
  styleUrls: ["./demo.component.scss"],
  encapsulation: ViewEncapsulation.None
})
export class DemoComponent implements OnInit {

demo.component.scss

ngx-datatable {
  .green-color {
    background: green;

    & div {
      color: #fff;
    }
  }
}

Whether you set the encapsulation to none or include the styles in the global style file, both methods achieve the same result of applying the style globally without any alterations.

Check out the demo 🔥

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

The Angular 2 ngSubmit.emit() function does not update the submitted property of the <myform> form

Whenever I run the code, the addResult() method property is triggered but the submitted property always remains empty. Any thoughts on why this might be happening? <form class="form-horizontal" (ngSubmit)="addResult()" #resultForm="ngForm"> &l ...

Guide to refreshing filters once data is updated in PrimeNG tables?

Whenever I add new rows to the table, the display updates dynamically. However, any filters I have applied only reflect the initial data. https://i.stack.imgur.com/5Nuxe.png For example, if I use the "startsWith" filter on a column labeled "Title" with a ...

The CSS overflow scroller trims the excess background color

Attempting to build a website, I encountered an issue with displaying a scroll bar. Despite using the CSS property overflow: auto, I faced another problem. Let me illustrate the issue through a simple example. I have an outer div with the style overflow: ...

Utilizing Angular's Mat-Table feature to dynamically generate columns and populate data in a horizontal manner

I am in need of a solution where I must populate the mat-table in a horizontal format with an array of JSON objects. The input array is as follows: [{ "SAMPLERULEID": 69, "SAMPLERULENAME": "Sample1", &q ...

Discover the simple way to insert a div within an href text using jQuery

Having issues validating my template on http://validator.w3.org. Any suggestions on how to rectify this using jquery? <a href="/video/213123/"><img src="/media/videos/tmb/213123/1.jpg" title="Funny Videos" alt="Funny Videos" /><div class="T ...

Error: The "require" function is not recognized in this context. (Unknown function) @ ng2-translate.ts:2

Encountering the following error: Uncaught ReferenceError: require is not defined(anonymous function) @ ng2-translate.ts:2 The issue arises from the line where I'm importing @anguar/http import {provide} from '@angular/core'; import {Http ...

Align text to the center vertically on the screen

I am struggling to vertically center my text on a page. Whenever I click a button, the page becomes gray with a loading message. Although I've managed to horizontally center it, vertical alignment is posing a challenge. CSS .LockOff { display: n ...

Revamping Tab Styles with CSS

Currently, I am working on a mat tab project. The code snippet I am using is: <mat-tab-group> <mat-tab [label]="tab" *ngFor="let tab of lotsOfTabs">Content</mat-tab> </mat-tab-group> If you want to see the liv ...

Is there a way to get rid of those pesky red lines that appear when declaring variables in a .scss file in VS

Encountering red lines when defining variables in a .scss file using VS Code. The error message reads as follows: I have attempted various settings configurations in VS Code, but none seem to resolve the issue. Any suggestions for fixing this problem? ...

Unresponsive CSS styles on a specific DIV element

Here is the HTML code I am currently working with: <body> <section id="info"> <div class="status"> ... I have been attempting to apply styles to the div with a class of 'status' using my CSS file linke ...

Live Server in VS Code not refreshing automatically as expected

My problem is with VS Code and Live Server for HTML CSS. I expected the page to automatically reload after editing my HTML, but that's not happening. Even though I have Auto-Save enabled, Live Server isn't updating or refreshing my page automati ...

Tips for hiding a div only on mobile devices while always displaying it on large screens using AngularJS or CSS

How can I use Angularjs or css to hide a div on mobile devices only, ensuring that it is always displayed on large screens? ...

What is the best way to ensure that my two sections stay vertically aligned, even when they have varying amounts of content and are scaled

I'm struggling to align two sections horizontally with varying content lengths, even when scaled. I attempted using display:flex in the .section part of my CSS, but it didn't yield the desired effect. Changing the flex direction also didn't ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

Struggling to manipulate the transparency of an image contained within a div element

I am struggling to achieve the desired effect of having an opaque image inside a transparent div. I have tried setting the opacity for both the image and the div, but it doesn't seem to be working as expected. Here is my jsFiddle Link for reference: ...

Issue with the scoring algorithm using Angular and Spring Boot

Hello, I have created a scoring algorithm to calculate scores, but I encountered an error in "salaireNet". ERROR TypeError: Cannot read properties of null (reading 'salaireNet') at ScoringComponent.calculateScore (scoring.component.ts:33:55) ...

4 innovative ways to customize internal CSS in Bootstrap

I'm just starting out with bootstrap and I could really use some guidance on how to customize it. I managed to create a sample site, but I'm struggling to make modifications beyond the basic bootstrap settings. I have a "container" with blue font ...

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

What are some alternative ways to arrange this main navigation bar?

Check out the website, below the map you'll find an unordered list: HTML code: <ul class="play_navigation"> <li class="active"><a href="#" class="barino_story_bottom">The Story</a></li> <li><a href="#" ...

Is it possible to include a component in an HTML file when the constructor of the component needs a parameter?

Recently delving into the world of AngularJs has been a captivating experience for me. I am aiming to develop a component with a constructor that accepts a parameter of type string. However, when I try to declare the selector on the HTML file, the componen ...