简体   繁体   中英

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

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.

You could use ngAfterViewInit lifecycle hook

ngAfterViewInit() {
  if (this.state == "closed") {
    this.state = "wided";
  }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM