gpt4 book ai didi

css - 从 html 属性绑定(bind)设置 div 背景图像

转载 作者:行者123 更新时间:2023-11-27 23:26:45 26 4
gpt4 key购买 nike

我正在尝试设置 background-image从后端以动态方式获取 div。我正在使用 django (djangorestframework)作为后端。我正在发送一个 http 请求,这是我收到的数据:

{
"user": "1ad54d3c-a012-431a-9e7a-8630fd9fb566",
"image": "api/media/users/1ad54d3c-a012-431a-9e7a-8630fd9fb566/tutorials/yyyy/_image/tutorialImage.png",
"title": "yyyy",
"description": "hgdhgdh",
"level": "professional",
"parts": 0,
"offical": false
}

这是 html:

<div class="tutorial-card">
<div class='tutorial-img' [style.background-image]="getTutorialImgURL(tutorial.image)">
</div>

getTutorialImageURL功能:

public getTutorialImgURL(path: string){
return `url("http://${config.backendDomain}/${path}")`;
} // config.backendDomain is "localhost:8000"

似乎没有向后端发送get请求(url路径是对的)

我尝试过的事情:

  • 更改 http 的前缀到“https”

    • 它可以工作,但后端还不支持https所以它返回 code 400
  • 使用 [ngStyle]="{'background-image': getTutorialImgURL(tutorial.image)}"

    • 仍然是正确的路径但是没有发送请求
  • 制作getTutorialImgURL返回完整样式 (return image-backgr: url("http://${config.backendDomain}/${path}")`)
    • 与所有不发送 http 请求的正确路径相同
  • 使用DomSanitizer (return this.sanitizer.bypassSecurityTrustStyle( url("http://${config.backendDomain}/${path}") );)
    • 仍然和以前一样:正确的路径不向后端发送 http 请求

(我不想使用 <img [src]='...'> )

最佳答案

绑定(bind)到 style 子属性似乎有问题,因此您可以使用 ngStyle 来定义完整的内联样式。使用示例组件:

@Component(
{
selector:'tutorial-image',
template:`<div [ngStyle]="{ 'background-image': 'url(' + imgUrl + ')'}"></div>`
})
export class TutorialImage {
@Input() path:string
imgUrl: string

ngOnInit(){
this.imgUrl= `http://${config.backendDomain}/${path}`
}
}

请注意,如果它托管在 https 上,它将无法从非 https 端点检索图像(混合内容错误)

解决方案改编自:Attribute property binding for background-image url in Angular 2

工作堆栈 Blitz :https://stackblitz.com/edit/angular-poxtf2

关于css - 从 html 属性绑定(bind)设置 div 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57742105/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com