Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind CSS 4 custom properties in Angular?

Tags:

css

angular

With the introduction of custom properties in CSS 4, I would like to bind them in Angular.

Normally, one would use custom properties like so:

<div style="--custom:red;">
    <div style="background-color: var(--custom);">
        hello
    </div>
</div>

However, when using Angular's binding mechanism, it does not result in a red rectangle:

<div [style.--custom]="'red'">
    <div style="background-color: var(--custom);">
        hello
    </div>
</div>

So how do I bind custom properties?

like image 305
Chris Smith Avatar asked Jul 28 '17 22:07

Chris Smith


People also ask

How would you implement CSS logic in an Angular application?

Angular components can be styled via global CSS the same as any other element in your application. Simply drop a `<link>` element on your page (typically in index. html) and you're good to go! However, Angular additional gives developers more options for scoping your styles.

What is CSS custom properties?

Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.

What is custom property binding in Angular?

Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button functionality, set paths programmatically, and share values between components.


1 Answers

I think you currently cannot bind that easy, BUT there's a work around. As custom properties benefit from cascading you could set the property in your component and use it elsewhere inside it.

constructor(
  private elementRef: ElementRef
) { }

ngOnInit() {
  this.elementRef.nativeElement.style.setProperty('--custom', 'red');
}

I took it from here https://github.com/angular/angular/issues/9343#issuecomment-312035896, but the renderer solution is not working for me

like image 83
subarroca Avatar answered Sep 21 '22 12:09

subarroca