简体   繁体   中英

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

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM