2

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 }} + ')'}">
Krunal
  • 77,632
  • 48
  • 245
  • 261
Kravitz
  • 2,769
  • 6
  • 26
  • 53

3 Answers3

4

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.

Koronos
  • 547
  • 4
  • 16
1

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • still no joy with that.. it gives me undefined – Kravitz May 27 '16 at 19:50
  • Is it just me or is anybody else getting slightly disillusioned with Angular 2... it promises so much but even the most trivial of things requires so many steps to get right – Kravitz May 27 '16 at 20:05
1

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>
calbear47
  • 1,060
  • 2
  • 18
  • 38