3

In the html I can use ngStyle to write:

<some-element [ngStyle]="objExp">...</some-element>

Where objExp returns

    return {
        "background": "red"
    };

This works, and turns the background of the element to red.

There are times when I want a fallback values. For example, if I was dealing with gradients I would need -webkit-linear-gradient, -o-linear-gradient then linear-gradient. I can't add multiple values with the same key to a javascript object.

I guessed at

return { "background": ["red", "blue"] }

but that doesn't seem to work. I've also tried { "background: "red, blue" }

I don't want to use the <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> because that loads complexity repetitively into my html. I can't use [style]="expresionThatGivesAString" because it breaks in Safari.

"red" and "blue" are set at runtime, which is why I'm binding them straight to the element. So putting them in classes isn't an option.

How do I set multiple background values using ngStyle?

Nathan Cooper
  • 6,262
  • 4
  • 36
  • 75

1 Answers1

0

For complex rules, use ngClass directive instead. Setup classes in your component styles

component.css

.gradient1 {
  background: -webkit-linear-gradient(red, yellow);
  background: -o-linear-gradient(red, yellow);
  background: -moz-linear-gradient(red, yellow);
 }

.gradient2 {
  background: -webkit-linear-gradient(black, white);
  background: -o-linear-gradient(black, white);
  background: -moz-linear-gradient(black, white);
 }

Your component should determine which class is active; the class in turn applies the fallback values as defined in the CSS.

component.ts

// Will determine which class to apply.
getClass(){
  return someCondition ? 'gradient1' : 'gradient2';
}

Then in your template, just apply the class by binding to the function result.

component.html

<some-element [ngClass]="getClass()">...</some-element>
BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
  • 1
    Thanks for your effort, but the colours come at runtime, which means I can't use this. I'll make that more clear in my answer – Nathan Cooper Jul 12 '17 at 07:33