Reputation: 19262
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?
Upvotes: 1
Views: 1050
Reputation: 122032
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};
`);
}
Upvotes: 2