onInit中的Angular2动画不起作用

时间:2016-12-26 12:09:40

标签: angular animation angular-animations

在Angular2应用程序中,我正在尝试制作动画

这是组件的html:

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

   </div>

这是动画:

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))])
  ]

当页面加载时,我将要动画这个动画:

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

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

            this.state="wided";
         }
}

2 个答案:

答案 0 :(得分:0)

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

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

否则,this.state = "wided"类重新定义了初始closed状态,并且组件初始化为wided为初始化而没有动画。

答案 1 :(得分:0)

您可以使用ngAfterViewInit生命周期挂钩

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