Angular 2 - background image into a html file using ngStyle

为君一笑 提交于 2019-12-06 04:52:44

You don't need use {{}} for call some propiety than you put in a directive, like this:

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

@Component({
  selector: 'my-app',
  template: `
<div class="image" [ngStyle]="{'background-image':'url(' + object.link + ')'}"></div>
  `,
  styles: [`
  .image{width:100px;height:100px; border: solid 1px black;}
  `]
})
export class AppComponent {
  selectedColor:any = 0;
  color;

  object = {
    link: "http://lorempixel.com/100/100"
  }

  constructor(){
  }
}

You can see the example in this Plunker. Enjoy.

Günter Zöchbauer

Don't use [] and {{}} together, it's either the one or the other:

<div class="table-wrap featuredimg"  [ngStyle]="{'background-image': 'url(' + project.projectimage + ')'}">

See also In RC.1 some styles can't be added using binding syntax

Just to build on top of Gunter's answer, this works with the async pipe as well.

 <div md-card-avatar class="profile_header" 
  [ngStyle]="{'background': 'url(' + (usergravatar$ | async) + ')'}"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!