Javascript 使用 ngFor 时的 angular 4 样式背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44526691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:35:10  来源:igfitidea点击:

angular 4 style background image when using ngFor

javascriptcssjsonangular

提问by eslam masoud

I have problem with background image url. i have array have images url how can I use it in background image url

我的背景图片网址有问题。我有数组有图像 url 如何在背景图像 url 中使用它

<div class="col-lg-3 col-md-3 col-sm-6" *ngFor="let course of courses"><a>
    </a><div class="box"><a>
        <div class="box-gray aligncenter"  [style.backgroundColor]="course.imageUrl" >
        </div>
        </a><div class="box-bottom"><a >
            </a><a >{{course.name}}</a>
        </div>
    </div>
</div>

回答by Hitmands

Refer to this one Angular2 dynamic background images

参考这张Angular2动态背景图片

// inappropriate style.backgroundColor 
[style.backgroundColor]="course.imageUrl"

// style.backgroundImage
[style.backgroundImage]="'url('+ course.imageUrl +')'"

回答by eslam masoud

thank you for your answers, the correct code is

谢谢你的回答,正确的代码是

[ngStyle]="{'background-image':'url(' + course.imageUrl + ')'}">

回答by Pankaj Parkar

You should use backgroundinstead of backgroundColor

你应该使用background而不是backgroundColor

[style.background]="'url('+course.imageUrl+')'"

回答by Coder Girl

you can do it by adding url path in a single variable. for example

您可以通过在单个变量中添加 url 路径来实现。例如

bgImageVariable="www.domain.com/path/img.jpg";

and

second way
[ngStyle]="{'background-image': 'url(' + bgImageVariable + ')'}"
[ngStyle]="{'background-image': 'url(' + bgImageVariable + ')'}"