角度2动画错误

时间:2017-04-03 12:10:48

标签: angular angular-animations

我尝试用Angular制作一个简单的动画:

import { Component, animate, trigger, state, style, transition } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('divState', [
      state('normal', style({
        'background-color': 'red',
        transform: 'translateX(0)'
      })),
      state('highlighted', style({
        'background-color': 'blue',
        transform: 'translateX(100px)'
      })),
      transition('normal <=> highlighted', animate(300))
    ])
  ]
})


export class AppComponent {
  private state;

  constructor(){
    this.state = 'normal';
  }

  onAnimate() {
    this.state == 'normal' ? this.state = 'highlighted' : this.state = 'normal';
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div>
    <button (click)="onAnimate()">Switch</button>
</div>
<div style="height: 20px">
<div 
    style="width: 100px; height: 100px" [@divState]="state">
</div>

但如果我点击按钮就说:

  

未捕获的ReferenceError:未定义onAnimate       在HTMLButtonElement.onclick((index):13)

有人知道那里有什么问题吗?

编辑:按钮现在可以正常工作,但动画仍然失败并且div也没有显示出来。

3 个答案:

答案 0 :(得分:1)

您必须导入依赖。

import {style,animate,state,keyframes } from '@angular/core';

运气!

答案 1 :(得分:0)

应如下所示。使用(click)代替(onclick),因为angular 2将触发zone(),触发对异步实现的更改检测(事件点击,XHR,)

<div>
    <button (click)="onAnimate()">Switch</button>
</div>

答案 2 :(得分:0)

你应该在这里使用事件绑定:

<button (click)="onAnimate()">Switch</button>

查看教程以获取有关事件绑定的更多详细信息:https://angular.io/docs/ts/latest/guide/user-input.html

相关问题