Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control CSS variable from Angular 5

Tags:

css

angular

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

like image 943
Srikanth Sharma Avatar asked Apr 18 '18 15:04

Srikanth Sharma


People also ask

Can I use CSS in angular?

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.

How do I use dynamic CSS in angular 6?

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.

Can we use both CSS and SCSS in angular?

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.


1 Answers

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

like image 140
ashfaq.p Avatar answered Sep 21 '22 18:09

ashfaq.p