Srikanth Sharma
Srikanth Sharma

Reputation: 2037

Control CSS variable from Angular 5

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

Upvotes: 20

Views: 52688

Answers (3)

Asaf Agranat
Asaf Agranat

Reputation: 402

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

Upvotes: 7

ashfaq.p
ashfaq.p

Reputation: 5469

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

Upvotes: 36

Alexis Poo
Alexis Poo

Reputation: 80

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

Upvotes: -4

Related Questions