angularanimationangular-animations

Angular2 animation inside onInit does not work


In Angular2 app, i am trying to make an animation

Here is component's html:

   <div  [@playBox]="state" id="toPlay" class="playBox rounded-box">

   </div>

Here is the animation:

animations:[
    trigger('playBox',[
            state('closed',style({
            width: '5%',
            backgroundColor:'red',
            transform:'translateX(0)'
          })),
          state('wided',style({
                width: '100%',
                border: '3px solid red',
                backgroundColor:'transparent'
          })),transition('closed => wided',animate(4000))])
  ]

I am going to triger this animation when the page get loaded:

export class AppComponent implements OnInit{
  state="closed";
 public ngOnInit(): any
 {

        if(this.state=="closed"){

            this.state="wided";
         }
}

Solution

  • Not sure this is the most proper and elegant solution but changing state in the next tick will trigger animation as expected:

    public ngOnInit(): any {
      if (this.state == "closed") {
        setTimeout(() => this.state = "wided")
      }
    }
    

    Otherwise, this.state = "wided" kind of redefines initial closed state and component gets initialized with wided as initial without animation.