Angular how to use ng-deep but still affect only one component?

2.7k Views Asked by At

In an Angular application, using Angular Material for themes, I'm trying to update a css class in a component when my theme changes to dark.

This would work, but it would affect all components, loosing the encapsulation:

::ng-deep .dark-theme { // must have ::ng-deep to see .dark-theme on body
  .action-button:hover {
    color: #ffffff;
  }
}

How can I have same result, but only for one component?

I've tried this as mentioned here but doesn't seems to work for me:

::ng-deep .dark-theme {
  :host .action-button:hover {
    color: #ffffff;
  }
}
// OR
:host ::ng-deep .dark-theme .action-button:hover {
  color: #ffffff;
}
1

There are 1 best solutions below

0
Omkar Nilakhe On

Try this :

As we set the View Encapsulation(Emulated) to the required component the styles will be applied only to the elements within the component's template.

@Component({ selector: 'app-emulated-encapsulation', template: '', styles: '', encapsulation: View Encapsulation .Emulated, })

With the limited info provided to actually test the scenario, you can avoid using ng-deep and host too if setting the Encapsulation property in @Component block fixes your issue.

Pls refer - https://angular.io/guide/view-encapsulation for further info.