ngStyle(angular2)を使用して背景画像を追加する方法


102

ngStyleを使用して背景画像を追加する方法 私のコードは動作しません:

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

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

ngStyle属性で角括弧を使用する理由
ギャル

参照してくださいstackoverflow.com/questions/37076867/... RC.1の関連問題について
ギュンターZöchbauer

回答:


228

私はこれを試すことができると思います:

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

あなたのngStyle表現を読んで、あなたはいくつかの「」を逃したと思います...


テスト済み。RC.1。での作業 彼らがここ
Lucio Mollinedo

4
私は好むthis.photo = `url(${photo})`; [style.background-image]='photo'
slideshowp2

4
画像のURL(画像名)にスペースが含まれていると、無音[ngStyle][style.background-image]レンダリングが失敗する場合があることに注意してください。
vulp

83

また、これを試すことができます:

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


3
@ redfox05 ngStyleは構文糖であると思います。主な違いは、ngStyleでは複数のcssルールを適用できますが、[style。<css_prop>]では1つしか適用できないことです。次の等価です: <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 2017年

このアプローチを使用して条件付きスタイリングを行う方法は?写真がnullでないかどうかを確認し、このスタイルのみを適用する場合はどうでしょうか。
Pankaj

25
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>

こちらもご覧ください


6

スタイルがサニタイズされているようです。バイパスするには、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>



3

URLにスペースが含まれていて、URLエンコードする必要があったため、背景画像が機能しませんでした。

エスケープする必要のある文字を含まない別の画像URLを試すことで、これが問題であるかどうかを確認できます。

これは、encodeURI()メソッドに組み込まれたJavaScriptを使用するだけで、コンポーネント内のデータに対して行うことができます。

個人的には、テンプレートで使用できるようにパイプを作成したかったのです。

これを行うには、非常に単純なパイプを作成できます。例えば:

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>

0

次の2つの方法を使用できます。

方法1

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

方法2

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

注:URLを char 」で囲むことが重要です。


0

URLにスペースが含まれているため、ほとんどの場合、画像は表示されません。あなたの場合、あなたはほとんどすべてを正しくやった。1つを除いて-css Ieでbackground-imageを指定する場合のように、単一引用符を追加していません

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

これを行うには、HTMLのquot文字を\ 'でエスケープします。

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

0

私のソリューションは、if..elseステートメントを使用しています。不必要なフラストレーションを避けたい場合は、常に変数が存在し、設定されていることを確認することをお勧めします。それ以外の場合は、代替画像を用意してください。background-position: centerなど、複数のスタイルプロパティを指定することもできます。

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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.