jaks
jaks

Reputation: 4587

Angular 4 CSS DIV background-image binding doesn't work

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

Upvotes: 0

Views: 1801

Answers (1)

andreim
andreim

Reputation: 3503

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

Upvotes: 1

Related Questions