Joker Bench
Joker Bench

Reputation: 228

Change the background with url in angular

Good day,

I'm trying to change my background url after I click the button. By default, I have this style on my css.

.whole-container {
    background: linear-gradient(
                               rgba(0, 0, 0, 2.5),
                               rgba(0, 0, 0, 2.5)
    ), url('link-with-random-image') no-repeat center center fixed;

And my sample HTML looks like this:

<div class="whole-container">
    ....
</div>

My problem is, I want to trigger the change of background without reloading the page.

What I did so far, is like this:

app.component.html

<div class="whole-container" [ngStyle]="{'background': wholeContainerStyle}">
    ...
</div>

app.component.ts

changeBg(){
    this.wholeContainerStyle = "linear-gradient(rgba(0, 0, 0, 2.5),rgba(0, 0, 0, 2.5)),url('link-with-random-image') no-repeat center center fixed;"
}

But the background image doesn't change.

Any help?

Upvotes: 0

Views: 280

Answers (1)

Barremian
Barremian

Reputation: 31105

If you need to toggle between two different styles, you could use ngClass directive.

CSS

.whole-container-1 {
  background: 
    linear-gradient(rgba(0, 0, 0, 2.5), rgba(0, 0, 0, 2.5)), 
    url('link-with-random-image') no-repeat center center fixed;
}

.whole-container-2 {
  background: 
    linear-gradient(rgba(0, 0, 0, 2.5), rgba(0, 0, 0, 2.5)), 
    url('other-link-with-random-image') no-repeat center center fixed;
}

Controller

export class AppComponent {
  defaultStyle = true;
  ...
}

Template

<div [ngClass]="defaultStyle ? 'whole-container-1' : 'whole-container-2'">
    ...
</div>

<button (mouseup)="defaultStyle = !defaultStyle>Toggle style</button>

Update

Working example: Stackblitz

Upvotes: 1

Related Questions