Control CSS variable from Angular 5

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


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

Tags:

Css

Angular