How to bind CSS 4 custom properties in Angular?

Viewed 1666

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?

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

Related