1

Let's say I want to write a component in Angular 2 that has two input arguments: colorOne and colorTwo. What the component should do is to fill a <div> with the gradient of those two colors.

If I just wanted to give the div a background color of colorOne it wouldn't be a problem, I could just use <div [style.background]="colorOne" class="my-box"></div>. However, if I want to give it a background gradient, I wouldn't know how to do it nicely, because background-gradient needs to be vendor prefixed. The only solution I could think of was checking in javascript which browser is used. Something like:

  public get headerColor () {

    //... determine the browser

    let backgroundStyle = `linear-gradient(left top, ${this.colorOne}, ${this.colorTwo})`;
    if (isWebkit) {
      backgroundStyle = "-webkit-" + backgroundStyle;
    } else if (isO) {
      backgroundStyle = "-o-" + backgroundStyle;
    } else if (isMoz) {
      backgroundStyle = "-moz-" + backgroundStyle;
    }

    return backgroundStyle;

  };

and then use <div [style.background]="headerColor" class="my-box"></div>. Is there a better solution than this?

0

1 Answer 1

2

You could return a single string that contains all of the various prefixed values; only the relevant one will be used:

<div [style]="stylish" class="my-box"></div>
import { DomSanitizer } from '@angular/platform-browser';

...

constructor(private sanitizer: DomSanitizer, ...) { ... }

get stylish() {
    let basicStyle = `linear-gradient(left top, ${this.colorOne}, ${this.colorTwo})`;
    return this.sanitizer.bypassSecurityTrustStyle(`
      background: -o-${basicStyle};
      background: -moz-${basicStyle};
      background: -webkit-${basicStyle};
    `);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, this works! I tried this, but without the sanitizer, so it didn't work before when I tried.

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.