如何使用ngStyle(angular2)添加背景图像?

151

如何使用ngStyle添加背景图片?我的代码不起作用:

this.photo = 'http://dl27.fotosklad.org.ua/20121020/6d0d7b1596285466e8bb06114a88c903.jpg';

<div [ngStyle]="{'background-image': url(' + photo + ')}"></div>

为什么在ngStyle属性上要使用括号? - gal
请参阅 https://dev59.com/SVoU5IYBdhLWcg3wzZPw 了解与 RC.1 相关的问题。 - Günter Zöchbauer
9个回答

298

我认为你可以尝试这个:

<div [ngStyle]="{'background-image': 'url(' + photo + ')'}"></div>

从您的ngStyle表达式中我猜测您错过了一些" ' "...


测试通过。与RC.1一起工作正常。根据这里的说法,RC.2及更高版本不需要这个。 - Lucio Mollinedo
8
我更喜欢 this.photo = \url(${photo})`; 而不是[style.background-image]='photo'`。 - Lin Du
6
请注意,图片 URL(图片名称)中的空格可能会导致[ngStyle][style.background-image]无声渲染失败。 - iAmV
这很好。我曾经使用过它,效果很好。不错的选择。 - BeardedPrince

101

另外你也可以尝试这个:

[style.background-image]="'url(' + 照片地址变量名 + ')'"


4
我认为ngStyle是一种语法糖。主要的区别是ngStyle允许您应用多个CSS规则,而[style.<css_prop>]只允许一个。下面两个示例具有相同的效果:<div [ngStyle]="{ color: 'red', 'font-size': '22px' }">First</div><div [style.color]="'red'" [style.font-size.px]="22">Second</div> - Todmy
我使用了这种 [style.css] 方法,但是我无法让 [style.background-repeat] 正常工作,你知道为什么吗? - Anders Metnik
如何使用这种方法进行条件样式设置?比如说,如果我想检查照片不为空,然后才应用这个样式怎么办? - Pankaj

34

9

看起来你的样式已经被清理了,要绕过它,请尝试使用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>


7

使用替代方案

[ngStyle]="{'background-image':' url(' + instagram?.image + ')'}"

6

我的背景图片无法正常工作,因为URL中有一个空格,所以我需要对其进行URL编码。

您可以通过尝试使用不需要转义的字符的不同图像URL来检查是否存在此问题。

您可以使用JavaScript内置的encodeURI()方法在组件中执行此操作。

个人而言,我想创建一个管道,以便它可以在模板中使用。

要实现这一点,您可以创建一个非常简单的管道。 例如:

src/app/pipes/encode-uri.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'encodeUri'
})
export class EncodeUriPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return encodeURI(value);
  }
}

src/app/app.module.ts

import { EncodeUriPipe } from './pipes/encode-uri.pipe';
...

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule
    ...
  ],
  exports: [
    ...
  ],
 declarations: [
    AppComponent,
    EncodeUriPipe
 ],
 bootstrap: [ AppComponent ]
})

export class AppModule { }

src/app/app.component.ts

import {Component} from '@angular/core';

@Component({
  // tslint:disable-next-line
  selector: 'body',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {
  myUrlVariable: string;
  constructor() {
    this.myUrlVariable = 'http://myimagewith space init.com';
  }
}

src/app/app.component.html

<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>

4
您可以使用两种方法:

方法 1

<div [ngStyle]="{'background-image': 'url(&quot;' + photo + '&quot;)'}"></div>

方法二

<div [style.background-image]="'url(&quot;' + photo + '&quot;)'"></div>

注意:重要的是要使用字符将URL括起来。

4

通常图片无法显示是因为URL中包含空格。在您的情况下,您几乎做对了所有事情。除了一件事 - 您没有像在CSS中指定 background-image 时所做的那样添加单引号。

.bg-img {                \/          \/
    background-image: url('http://...');
}

为在HTML中转义引号字符,需通过 \ 进行转义。
                                          \/                                  \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>

3

我的解决方案使用if..else语句。如果您想避免不必要的挫败感,最好进行检查以确保变量存在且已设置。否则,在需要时提供备用图像;您还可以指定多个样式属性,例如background-position: center等。

<div [ngStyle]="{'background-image': this.photo ? 'url(' + this.photo + ')' : 'https://placehold.it/70x70', 'background-position': 'center' }"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接