Angular2 animation inside onInit does not work

2.2k views Asked by At

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";
         }
}
3

There are 3 answers

0
dfsq On BEST ANSWER

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.

1
Дима Афонин On

You could use ngAfterViewInit lifecycle hook

ngAfterViewInit() {
  if (this.state == "closed") {
    this.state = "wided";
  }
}
0
Алексей Коробов On

Please using:

transition('void => wided',animate(4000))])

the stage void mean when element not exists in DOM and then appears
About void state see documentation