[英]How to set background image in angular 6?
Here i want to set placehoder image and for that i use commonurl path (this.commonUrlObj.commonUrl) instead of ( http://localhost:3000 ) so how to set image in background-image using commonurl in angular 6? 在这里我想设置placehoder图像,为此我使用commonurl路径(this.commonUrlObj.commonUrl)而不是( http:// localhost:3000 ),那么如何在角度6中使用commonurl在背景图像中设置图像?
category.component.html category.component.html
<img [src]="url" style="height: 400px;width: 400px" [ngStyle]="{'background-image': getUrl()}">
category.component.ts category.component.ts
getUrl(){
return "url('this.commonUrlObj.commonUrl/placeholder.jpg')";
}
common-class.ts 共class.ts
export class CommonClass {
constructor(public commonUrl : string = 'http://localhost:3000'){};
}
getUrl(){
return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}
Maybe I didn't understand your problem but is this what you wanted to do ? 也许我不明白您的问题,但这是您想做的吗?
getUrl(){
return `url('${this.commonUrlObj.commonUrl}/placeholder.jpg')`;
}
You can't have an background image for an image. 您不能有背景图片。 What you can do is wrap a
div
and give it an background: 您可以做的是包装一个
div
并为其提供背景:
getUrl(){
return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}
<div [ngStyle]="{'background-image': getUrl()}>
<img [src]="url" style="height: 400px;width: 400px">
</div>
As per docs in Angular.io you can give ngStyle an ObjExp. 根据Angular.io中的文档,您可以给ngStyle一个ObjExp。 Like this.
像这样。
TS
// Not in the question but don't use a constructor to define vars
private commonUrl: string = 'localhost:3000'; // Could have this as an env variable
getBackground() {
return {'background-image': `url(${this.commonUrl}/placeholder.png)`};
}
HTML
<div [ngStyle]="getBackground()"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.