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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34875426/
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 16:59:28  来源:igfitidea点击:

How to add background-image using ngStyle (angular2)?

javascripthtmlcssangular

提问by Ignat

How to use ngStyle to add background-image? My code doesn't work:

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

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

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

回答by Thierry Templier

I think you could try this:

我想你可以试试这个:

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

From reading your ngStyleexpression, I guess that you missed some "'"...

看你的ngStyle表情,我猜你漏掉了一些“'”......

回答by Todmy

Also you can try this:

你也可以试试这个:

[style.background-image]="'url(' + photo + ')'"

[style.background-image]="'url(' + photo + ')'"

回答by Günter Z?chbauer

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>

See also

也可以看看

回答by Uliana Pavelko

Looks like your style has been sanitized, to bypass it try using bypassSecurityTrustStyle method from DomSanitizer.

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

回答by Vijay Chauhan

Use Instead

改用

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

回答by Tom Benyon

My background image wasn't working because the URL had a space in it and thus I needed to URL encode it.

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

You can check if this is the issue you're having by trying a different image URL that doesn't have characters that need escaping.

您可以通过尝试不包含需要转义的字符的其他图像 URL 来检查这是否是您遇到的问题。

You could do this to the data in the component just using Javascripts built in encodeURI()method.

您可以仅使用encodeURI()方法中内置的 Javascript 对组件中的数据执行此操作。

Personally I wanted to create a pipe for it so that it could be used in the template.

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

To do this you can create a very simple pipe. For example:

为此,您可以创建一个非常简单的管道。例如:

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

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

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

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

src/app/app.component.html

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

回答by riofly

You can use 2 methods:

您可以使用 2 种方法:

Method 1

方法一

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

Method 2

方法二

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

Note: it is important to surround the URL with "char.

注意:用"字符包围 URL 很重要。

回答by simply good

Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.

大多数情况下,图像不会显示,因为您的 URL 包含空格。在你的情况下,你几乎做对了一切。除了一件事 - 如果你在 css Ie 中指定背景图像,你没有像你那样添加单引号

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

To do so escape quot character in HTML via \'

为此,通过 \' 转义 HTML 中的 quot 字符

                                          \/                                  \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>

回答by AllJs

My solution, using if..else statement. It is always a good practice if you want to avoid unnecessary frustrations, to check that your variable exists and is set. Otherwise, provide a backup image in case; You can also specify multiple style properties, like background-position: center, etc.

我的解决方案,使用 if..else 语句。如果您想避免不必要的挫折,检查您的变量是否存在并已设置,这始终是一个好习惯。否则,请提供备用图片以防万一;您还可以指定多个样式属性,例如background-position: center等。

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