chnselim
chnselim

Reputation: 254

Change background color with Angular animations

I want to change my gradient background color to another one when clicked a button. Here's an example from Angular Docs as i show below. This code works fine with normal colors(changes slowly during 1000ms -as what i want-) but not for gradient colors (changes immediately after 1000ms).

animations: [
    trigger('heroState', [
      state('black', style({
         background: 'linear-gradient(to right, #2c2d34, #242424)'
      })),
      state('green',   style({
         background: 'linear-gradient(to right, #2c2d34, #467a5e)'
      })),
  transition('black => green', animate('1000ms ease-out')),
  transition('green => black', animate('1000ms ease-in'))
])


<section class="bg-area" [@heroState]="state"></section>

Upvotes: 3

Views: 12644

Answers (3)

Joosep Parts
Joosep Parts

Reputation: 6235

If your looking looking to transition gradients you could play with pseudo elements or changing opacity. Apply same idea to animations: [] if you wish.

<div class="greenbg" [ngClass]="{'show' : isSolved, 'hide': !isSolved}"></div>
<div class="graybg" [ngClass]="{'show' : !isSolved, 'hide': isSolved}"></div>
.greenbg {
  background: radial-gradient(circle at center, rgba(161, 255, 67,0.4) 0%, #1a1a1a 100%);
  width: 100vw;
  height: 100vh;
  position: absolute;
}

.graybg {
  background: radial-gradient(circle at center, rgba(148, 148, 148, 0.4) 0%, #1a1a1a 100%);
  width: 100vw;
  height: 100vh;
  position: absolute;
}

.show {
  opacity: 1;
  transition: opacity 1s;
}

.hide {
  opacity: 0;
  transition: opacity 1s;
}
isSolved = false;

Upvotes: 0

Aamir Khan
Aamir Khan

Reputation: 3031

This code works fine with normal colors(changes slowly during 1000ms -as what i want-) but not for gradient colors (changes immediately after 1000ms)

The reason for this is that linear-gradient is not an animatable css property.

As the other answer mentioned, you can use a hacky approach using opacity and pseudo elements. Here is a nice tutorial on doing exactly this: https://medium.com/@dave_lunny/animating-css-gradients-using-only-css-d2fd7671e759

Upvotes: 2

Fussel
Fussel

Reputation: 1865

Linear-Gradient seem not to support tansitions as of now, so you would have to find a work-around for that. Something you could try could be setting the opacity of two elements which overlay each other. Something like this.

It's definitly not an ideal solution but to kick off an idea for now and maybe it helps you

Upvotes: 3

Related Questions