如何使用 ngStyle 添加背景图片?我的代码不起作用:
this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg';
<div [ngStyle]="{'background-image': url(' + photo + ')}"></div>
如何使用 ngStyle 添加背景图片?我的代码不起作用:
this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg';
<div [ngStyle]="{'background-image': url(' + photo + ')}"></div>
我想你可以试试这个:
<div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div>
看你的ngStyle
表情,我猜你漏掉了一些“'”......
你也可以试试这个:
[style.background-image]="'url(' + photo + ')'"
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'
constructor(private sanitizer:DomSanitizer) {
this.name = 'Angular!'
this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
}
<div [style.background-image]="backgroundImg"></div>
也可以看看
看起来您的样式已被清理,要绕过它,请尝试使用 DomSanitizer 中的 bypassSecurityTrustStyle 方法。
import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {
public backgroundImg: SafeStyle;
@Input() myObject: any;
constructor(private sanitizer: DomSanitizer) {}
ngOnInit() {
this.backgroundImg = this.sanitizer.bypassSecurityTrustStyle('url(' + this.myObject.ImageUrl + ')');
}
}
<div *ngIf="backgroundImg.length > 0" [style.background-image]="backgroundImg"></div>
改用
[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"