2017-04-03 48 views
0

我試圖做一個簡單的動畫與角:角2動畫錯誤

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> 

但是,如果我按一下按鈕它說:

Uncaught ReferenceError: onAnimate is not defined at HTMLButtonElement.onclick ((index):13)

有誰知道那裏出了什麼問題?

編輯:按鈕現在可以工作,但動畫仍然失敗,div也不顯示。

+1

你的編碼是從angular2,但你正在導入angular1.x的文件? –

回答

0

它應該如下。使用(click),而不是(的onclick),因爲角2將觸發區(),它觸發異步實現變化檢測(點擊事件,XHR)

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

在angular2中它會被'(onclick)', –

+0

@PardeepJain在角2中(點擊)。 –

+0

這裏誤解了javascript和angular2,我的錯誤。 –

1

必須導入狀態依賴。

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

好運!