I am using Ionic(based on Angular) and I want to set an image as a background of a component with a color overlay above it. The code is correct when written into the .css file, however when it is dynamic(I substitute the values with variables) my syntax seems to not be right.
This does not affect the background of my component at all:
[ngStyle] = "{'background': 'linear-gradient('+colors[test.number]+','+colors[0]+'),url(../assets/img/test-'+test.number+'.jpg)'}"
However, this works but does not put an image as a background, only the color:
[ngStyle] = "{'background': 'linear-gradient('+colors[test.number]+','+colors[0]+')'}"
So my question is how can I correct the first code in order to have an image as well?
I think the value is being assigned as a style, but the browser is removing it when it's invalid.
Take this example:
<div [ngStyle]="{'background': 'fooBar'}"></div>
When I run the above example in Angular. I see this in the browser.
<div _ngcontent-c18="" ng-reflect-ng-style="[object Object]"></div>
The element is missing the background style when I use Chrome's inspector.
This tells me that Angular assigned the invalid CSS style but the browser ignored it.
This raises the question if one of your variables is undefined. It could be colors, colors[test.number], colors[0] or test.number.
Try using a function on the component to generate the style object, and logging this value to the console to ensure it's correct.
public getBackground(start, end, num) {
const style = {'background': `linear-gradient(${start},${end}),url(../assets/img/test-${num}.jpg)`};
console.log(style);
return style;
}
Then in the template
<div [ngStyle]="getBackground(colors[test.number],colors[0],test.number)"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With