Angular 2 - Animation transition not working

FlorisdG picture FlorisdG · Feb 10, 2017 · Viewed 13.7k times · Source

I need a transition between 2 colors OnClick. Right now, this is my code:

Typescript

animations: [
    trigger('menubarState', [
        state('false', style({backgroundColor:'#43a047'})),
        state('true', style({backgroundColor:'#333'})),
        transition('false => true', animate('1s')),
        transition('true => false', animate('1s'))
    ])
]

...

export class MenubarComponent {
  menuActive: boolean = false;
  onMenuClick () {
    if (this.menuActive == false) {
      this.menuActive = true;
    } else {
      this.menuActive = false;
    }
  }
}

HTML

<li [@menubarState]="menuActive" (click)="onMenuClick()">
      <a><span class="material-icons icon">apps</span></a>
</li>

This does change the background-color as it should. The change, however, is instant instead of a transition.

I am using the Chrome, latest version.

Answer

Aaron Krauss picture Aaron Krauss · Apr 10, 2017

This bit me for the longest time, and what fixed it was changing my state variable from a boolean type to a string type. So - instead of tracking true and false, track 'true' and 'false'. Per Angular's docs:

An animation state is a string value that you define in your application code.

Change your MenubarComponent class to this:

export class MenubarComponent {
  menuActive: string = 'false';
  onMenuClick () {
    if (this.menuActive === 'false') {
      this.menuActive = 'true';
    } else {
      this.menuActive = 'false';
    }
  }
}

I think it's dumb. Booleans are obviously good options for binary states.

More info: https://angular.io/guide/animations#states-and-transitions