6

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?

Chris Smith
  • 2,928
  • 4
  • 27
  • 59
  • You could try Sass instead. But have you thought about using a CSS class to include --custom... – JGFMK Jul 29 '17 at 09:54
  • @JGFMK Sass variables do not propagate like custom properties do. And I need to bind to the property which Angular can't do in a stylesheet. – Chris Smith Jul 29 '17 at 13:50
  • I'm not getting your comments there. 1) Sass vs Custom Properties. 2) Bind to the property which Angular can't do in a stylesheet. Can you elaborate? – JGFMK Jul 29 '17 at 21:08
  • https://stackoverflow.com/a/11195043/495157 - This is admittedly jQuery getting Sass variables... is that the kind of thing you were after... – JGFMK Jul 29 '17 at 21:19
  • I need Angular to bind to the properties so I can update them at run time via a REST API. Sass variables are like macros and do not propagate down the hierarchy if they change like custom properties do. – Chris Smith Jul 29 '17 at 22:03

1 Answers1

8

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

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
subarroca
  • 851
  • 7
  • 22