简体   繁体   English

onInit 内部的 Angular2 animation 不起作用

[英]Angular2 animation inside onInit does not work

In Angular2 app, i am trying to make an animation在 Angular2 应用程序中,我正在尝试制作 animation

Here is component's html:这是组件的 html:

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

   </div>

Here is the animation:这是 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:当页面加载时,我将触发这个 animation:

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:不确定这是最合适和最优雅的解决方案,但在下一个刻度中更改state将按预期触发动画:

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.否则, this.state = "wided"种重新定义了初始closed用状态和组分被初始化wided作为初始没有动画。

You could use ngAfterViewInit lifecycle hook您可以使用ngAfterViewInit生命周期钩子

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 stage void表示元素在 DOM 中不存在然后出现
About void state see documentation关于 void state 参见文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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