Angular 2 - Animation transition not working Angular 2 - Animation transition not working angular angular

Angular 2 - Animation transition not working


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


Expanding on the answer that Aaron Krauss provided. It is having issues with the direct interpretation of the true / false values; however, if you would rather not reference a string context, you can replace true and false in the above with the numbers 1 (true) and 0 (false). This proved to fix my issue and didn't require any annoying string interpretations.

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


Expanding even more on Aaron Krauss' answer:I don't want to transform my booleans into strings, so I defined a getter:

public menuActive: boolean = false;get menuState() {  return this.menuActive ? 'active' : 'inactive'}

And then in your animation definition (I merged the transitions since they are the same):

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

And to be complete, the template:

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