A. Bertrand
A. Bertrand

Reputation: 33

How to access local css class names from within the angular component

I need to access the generated css classname from within an angular component, in order to style a 3rd-party component.

Angular does some magic transformations on the local css classnames to enable scoping. I need to apply some custom styles to an ngx-datatable component. To do this, I need to pass it custom classnames. Because of what angular does to the classnames, these no longer match.

Adding the classnames to the global scope or using ::ng-deep both work, however I would rather not break the 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>

The way I see it I should be able to access some reference to the css class from within the component, say this._styles, which will then carry the generated name of the class at runtime, so I can do

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

Upvotes: 3

Views: 6005

Answers (2)

Alok
Alok

Reputation: 98

I think you are not able to propagate your styles to ngx-datatable.

You can use encapsulation: ViewEncapsulation.None within your @component but make sure you use it carefully as it will lead to some weird css behaviours.

Next, What you can do is create a container for your dashboard.html file like:

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

and inside your dashboard.scss you can reference the parent container

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

Upvotes: 2

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24474

Just put the css classes in the global style file ,otherwise you will need to use ::ng-deep,so my advice to put ngx-datatable in the global style file

check the ngx-datatable demo asset/app.css where the did the same

another option you can set the encapsulation: ViewEncapsulation.None on the component the the class name will be 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;
    }
  }
}

set the encapsulation to none or put the style in global style file are the same here because both ways will be the style globally without any change

demo 🔥

Upvotes: 1

Related Questions