Angular: Unable to set the background cover using ng-style directive

97 Views Asked by At

I have been adding a background image using ngStyle...

<div class="modal-header" [ngStyle]="{
                    background: 'url(api/myfile' 
                    + filteredProducts[index].imageURL + ')'}">

However, this css is invalidated

.modal-header {
    background-size: cover;
}

If I use a normal background image directly

.modal-header {
    background-size: cover;
    background-image: url('imageurl');
}

I have tried to add a background size in angular but this just screams wrong because I had to put background-size in quotes for the compiler to accept it

[ngStyle]="{background: 'url(api/myfile?filename=' 
                    + filteredProducts[index].imageURL + ')', 'background-size': cover}"

I finally tried using this property but all these failed

[style.background-size]="cover"

This too did not work

<div class="modal-header" [ngStyle]="
                {
                    'background-image': 'url(url'
                    + filteredProducts[index].imageURL+')', 
                    'background-size': 'cover',
                    'background-position': 'center'
                }
                ">
2

There are 2 best solutions below

0
On BEST ANSWER

Here is what I noticed when I did

var imgurl = 'api/myfile' + imageURL; 
console.log(imgurl);

This was the output
api/myfile imageURL

there was a space between the variables
I tried to use this but the white space was required in case the file name has spaces

var myRemoveSpaceAll = miner.replace(/ /g,'');

This was what I resorted to

 <div class="modal-header" [ngStyle]="
            {
             'background-image': 'url('+setstring(filteredProducts[index].imageURL)+')', 
             'background-size': 'cover',
             'background-position': 'center'
            }
 ">
 setstring(myfilename){
    var replacedstring = myfilename.replace(/ /g,'%20');
    var finalURL = "api/myfile" + replacedstring ;
    return finalURL ;
  }
0
On

Try this

<div class="modal-header" 
    [ngStyle]="{ 
       'background': 'url(api/myfile' + filteredProducts[index].imageURL + ') 
        no-repeat center center / cover' }">