Is there any way to control a CSS variable defined at a component's root level using Angular methods? In JavaScript, we have document.documentElement.style.setProperty()
when we set at root level.
In angular, can we use ':host' to declare css variable for global access within component? or do we need to use something like '::ng-deep :root'?
The following question also remains unanswered: Angular: Use Renderer 2 to Add CSS Variable
Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications.
create a new component and create a service to load dynamic css variables from API. Add style tag in template file and use variable values for properties. Load this template on all pages or on main template. On app build style will be moved to head tag.
With the help of Angular CLI, you can install CSS or SCSS on your project and start working on that in a suitable way. If you are working with the CSS or SCSS in your angular project then it is very easy for you as compared to most other frameworks.
Yes you can set variables in root scope:
:root {
--main-color: red
}
Yes you can use :host
selector to target element in which the component is hosted.
:host {
display: block;
border: 1px solid black;
}
You can also use, :host-context
to target any ancestor of the component. The :host-context() selector looks for a CSS class in any ancestor of the component host element, up to the document root.
:host-context(.theme-light) h2 {
background-color: #eef;
}
Note: ::ng-deep
or /deep/
or >>>
has been deprecated.
Read more about it here: special css selectors in angular
Just an additional information. It works both inside ':root' as well as ':host' We can set values to them by:
constructor(private elementRef: ElementRef) { }
then
this.elementRef.nativeElement.style.setProperty('--color', 'red');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With