0

template:

<div [style.background-image]="profileImage" ></div>

ts:

private profileImage: any;
private sanitizer:DomSanitizer

get photo from service:

this.profileImage = this.sanitizer.bypassSecurityTrustStyle("url("+ data.photo  + ")");

The binding is not working. I checked Chrome Dev tools, photo is not downloaded. When refreshing the page, it is working fine, but it has to work when the value is set in service. Tried with ngStyle also, it is not working.

Plunkr link https://plnkr.co/edit/IhVGjiImyfk0F1u6cWtG?p=preview

jaks
  • 4,407
  • 9
  • 53
  • 68
  • 1
    I do not understand how refreshing makes it work? It's still within the sample process. Can you show more code and project structure? – wannadream May 04 '17 at 18:42
  • Works fine in this plunkr https://plnkr.co/edit/jKMDoSEc8pq9BnhljiCw?p=preview – Aluan Haddad May 04 '17 at 18:55
  • plunkr is working for simple case, but when data is retrieved from service it is not – jaks May 05 '17 at 06:21
  • Here is the plunkr which shows that it doesn't work https://plnkr.co/edit/IhVGjiImyfk0F1u6cWtG?p=preview – jaks May 05 '17 at 06:40

1 Answers1

1

I updated a bit your code in order to work:

@Component({
  selector: 'my-app',
  template: `
    <div [style.background-image]="profileImage" style="width: 961px; height: 688px;"></div>
    <h2> {{message}}</h2>
  `,
})
export class App {

  profileImage: string;
  message: string;

  constructor(private sanitizer: DomSanitizer) {
    this.message = "Before async";
  }

  async ngOnInit() {
    await delay(2000);
    this.message = "Updating Photo";
    const url = 'https://4.bp.blogspot.com/--RBVfn6FzOI/Tq5kOxFGKEI/AAAAAAAACnM/LaiZLD0sUKY/s1600/cats.jpg';
    this.profileImage = this.sanitizer.bypassSecurityTrustStyle(`url(${url})`);
  }
}

Changes

1st: Change:

constructor(sanitizer: DomSanitizer)

into this:

constructor(private sanitizer: DomSanitizer)

Thus having the sanitizer as a member of the class in order to be accessible in ngOnInit().

2nd: Set the dimension of the <div>. This will not adjust automatically to your background image size. So I set width and height. Other solutions exist, like using the aspect ratio of the image, or keeping an invisible <img>. These and more are described in this answer.

3nd: Set the image HTTP scheme from http to https because you are receiving a warning in Plunker which serves content over https.

Updated Plunk

Community
  • 1
  • 1
andreim
  • 3,365
  • 23
  • 21
  • With quotes also not working. Check above plunkr link – jaks May 05 '17 at 11:15
  • @jaks sorry for that, my previous comment was stupid - `url(...) | url('...') | url("...")` are equivalent. I updated my comment with a working version. – andreim May 05 '17 at 12:05
  • The real problem was from the HTTP service, image was set. So it was not updating. Now put the code inside ngZone, and worked. – jaks May 06 '17 at 10:44