簡體   English   中英

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

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

如何使用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 + ')'}"

我的背景圖像不起作用,因為 URL 中有一個空格,因此我需要對其進行 URL 編碼。

您可以通過嘗試使用不包含需要轉義字符的其他圖片網址來檢查這是否是您遇到的問題。

您可以僅使用內置於encodeURI()方法的 Javascripts 對組件中的數據執行此操作。

我個人想為它創建一個管道,以便它可以在模板中使用。

為此,您可以創建一個非常簡單的管道。 例如:

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 { }

源代碼/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>

您可以使用 2 種方法:

方法一

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

方法二

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

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

大多數情況下,圖像不會顯示,因為您的 URL 包含空格。 就您而言,您幾乎做對了所有事情。 除了一件事 - 如果你在 css Ie 中指定背景圖像,你沒有像你那樣添加單引號

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

為此,請通過 \' 轉義 HTML 中的引號字符

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

我的解決方案,使用 if..else 語句。 如果您想避免不必要的麻煩,檢查您的變量是否存在並已設置始終是一個好習慣。 否則,提供備用圖像以防萬一; 您還可以指定多個樣式屬性,如background-position: center等。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM