1

I am using ngStyle property binding with my HTML element to bind dynamic style in my Angular component like below:

example.component.ts

.spinnerStyle = {
            'background': this.color,
            'background': `-moz-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-webkit-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-o-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `-ms-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)`,
            'background': `linear-gradient(to right, ${this.color} 10%, rgba(255,128,0, 0) 42%)`
        }

example.component.html

<div class="loader" [ngStyle]="spinnerStyle">Loading...</div>

As we can see my typescript file is having an object representing my CSS style. It is a valid CSS, but an invalid typescript object as it is having duplicate identifiers. My compilation is failing due to this. What should be the alternate approach?

1 Answer 1

1

Ok, I did a workaround for my style object by first creating it as string literal and then converted it to JSON object:

this.spinnerStyle = JSON.parse(`{ "background": "${this.color},background: -moz-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-webkit-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-o-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "-ms-linear-gradient(left, ${this.color} 10%, rgba(255,128,0, 0) 42%)",
            "background": "linear-gradient(to right, ${this.color} 10%, rgba(255,128,0, 0) 42%)"
        }`);

It worked like a charm...

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

6 Comments

Ok, I did a workaround for my style object by first creating it as string literal and then converted it to JSON object, but final json object will only keep the last property!!
question and answer are posted by you in same time. then why should you post this?
You can use ngClass. You put your css in your component.css, and use [ngClass]="{'spinnerStyle':condicion}" (when condition it's true, the class is applied)
@Ajmalsha Aftre posting the question I got it working by doing the workaround within minutes so shared the answer. But still it is not the solution as json object will ultimately keep the last key-value pair. But in CSS all values preserves.
@Eliseo My styles are very dynamic, and if I will use class it will be according to applied class. I will get these colors as input property.
|

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.