0

I have a stepper form (where you fill some fields, click next some other fields appears but its the same component) where I'd like a different background for each step. That means every time the user click a button, the background image has to change.

In order to try to achieve this I thought about using @HostingBinding like so:

@HostBinding('style.background-image')
bg_image = 'url(image_1.png)';

Then I'd a method that would be triggered every time the user clicks a button like so:

changeBg(img): void {
    bg_image = 'url(img.png)';
}

The above is pseudo-code, as I have some other logic wrapped around the whole thing, however the point that is that once the method is called, the background-image should update. On the html I have:

<div class="page-layout simple fullwidth"
 [ngStyle]="{ 'background': bg_image }">     

And that works to a degree. I set an initial image, and once the method is triggered for the first time, the bg images gets updated. The problem is that on the second time onwards that the method is called, the background-image property seems to add the new image, instead of replacing it. So the more I trigger the method, the more images are added/stacked to the background-image (I can see all images as they're patterns to be repeated).

To resolve the problem I tried to clear the property first like so:

changeBg(img): void {
    bg_image = '';
    bg_image = 'url(img)';
}

Which doesn't work. Funny enough, if I do:

changeBg(img): void {
    bg_image = '';
}

The background-image disappears. Any suggestions on how to resolve this?

WagnerMatosUK
  • 4,309
  • 7
  • 56
  • 95

2 Answers2

0

if you would use the image like as bg_image = 'https://picsum.photos/200/300' . You need to do in template

[ngStyle]="{ 'background': 'url(' + bg_image + ')' }"

if you would use the image like as

changeBg(img): void {
    bg_image = `url(${img})`;
}

You need to do in template [ngStyle]="{ 'background': bg_image }"

Ashot Aleqsanyan
  • 4,252
  • 1
  • 15
  • 27
0

try ChangeDetectorRef

ChangeDetectorRef.detectChanges()
nab
  • 568
  • 8
  • 20