19

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

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Srikanth Sharma
  • 1,509
  • 2
  • 15
  • 27

3 Answers3

34

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');

Srikanth Sharma
  • 1,509
  • 2
  • 15
  • 27
ashfaq.p
  • 5,379
  • 21
  • 35
7

The most constructive and modular way to use css vars in components (with viewEncapsulation) is as such:

// global css
:root {
   --main-color: red
   --alt-color: blue
}

// inside component component css
::ng-deep :root {
   --specific-css-var: var(--main-color)
}
:host {
   background-color: var(--specific-css-var)
}
:host(.conditional-class) {
   --specific-css-var: var(--alt-color)
}

NOTE: despite ::ng-deep being deprecated, it hasn't been replaced yet (and has no replacement), as can be read in several discussion like this

Asaf Agranat
  • 392
  • 3
  • 8
-4

Best thing for each component like a background color with out using ::ng-deep (which sets bg for all children)

import the following

import {ElementRef} from '@angular/core';

declare elementref in constructor

 constructor(private elementRef: ElementRef) {}

then call the function ngAfterViewInit()

ngAfterViewInit(){
    this.elementRef.nativeElement.ownerDocument.body.style.backgroundColor = ' white';
}

this sets bg to white but you can replace it with a hex color as well, so you can do that with every component

Alexis Poo
  • 82
  • 7
  • i didnt plan to touch the DOM. I wanted to animate CSS property of multiple DOM by controlling single CSS variable. any possibility in that direction? – Srikanth Sharma Apr 18 '18 at 17:05
  • on CSS you can call the object and id at same time like this: h4#firstname { background-color:red; } or class h4.classname{ background-color:red } – Alexis Poo Apr 18 '18 at 19:34