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?

5
  • You could try Sass instead. But have you thought about using a CSS class to include --custom... Commented Jul 29, 2017 at 9: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. Commented Jul 29, 2017 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? Commented Jul 29, 2017 at 21:08
  • stackoverflow.com/a/11195043/495157 - This is admittedly jQuery getting Sass variables... is that the kind of thing you were after... Commented Jul 29, 2017 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. Commented Jul 29, 2017 at 22:03

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.