简体   繁体   中英

Angular 2 - background image into a html file using ngStyle

I am pulling data from an API using an Angular 2 service.. I can output everything from the json api onto the page using something similar to this {{ project.title }} however i wish to output the url to a background image and I cant seem to get it working.. has anyone got any ideas or advice ?

Currently this is what I have. I've tried it without the curly braces also but nothing is working.

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM