简体   繁体   English

具有属性绑定的Angular 2动画不起作用

[英]Angular 2 animation with property binding not working

I'm trying to make a fade in animation to div. 我正在尝试使div的动画淡入淡出。

The code: 编码:

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

@Component({
    selector: 'my-app',
    template: `
        <button (click)="toggle()"> toggle div </div>
        <div [@visibilityChanged]="visibilityState">
            <p>Some text...</p>
        </div>`,
    animations:
        [
            trigger('visibilityChanged', [
                state('shown', style({opacity: 1})),
                state('hidden', style({opacity: 0})),
                transition('shown => hidden', animate('600ms')),
                transition('hidden=> shown ', animate('300ms')),
            ])
        ],
})

export class AppComponent {
    visibilityState : string = 'hidden';
    toggle(){
        if(this.visibilityState === 'hidden')
            this.visibilityState = 'shown';
        else
            this.visibilityState = 'hidden';
    }
 }

When I run this code "Some text..." is shown although the visibility state is 'hidden'. 当我运行此代码时,尽管可见性状态为“隐藏”,但仍显示“ Some text ...”。 The toggle event is not working and other click events in the code do not react. 切换事件不起作用,代码中的其他单击事件也不起作用。 When I remove the div: 当我删除div时:

 <div [@visibilityChanged]="visibilityState">
    p>Some text.../p>
 </div>`,

The program is working properly but I cannot preform the fade-in/out animation. 该程序运行正常,但无法执行淡入/淡出动画。 Why it doesn't work? 为什么不起作用? Thanks a lot! 非常感谢!

Your code looks fine. 您的代码看起来不错。 As far as I can see you are using wrong imports. 据我所知,您使用了错误的导入。

Starting with Angular 4, animations are in their own package instead of with @angular/core so your import statement will look like this instead: 从Angular 4开始,动画位于它们自己的包中,而不是@ angular / core,因此您的import语句将如下所示:

import { trigger, style, transition, animate, group } from '@angular/animations';

You also have to import BrowserAnimationsModule. 您还必须导入BrowserAnimationsModule。 So for example in your AppModule: 因此,例如在您的AppModule中:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  // ...
  imports: [BrowserAnimationsModule]
})
export class AppModule { }

If you don't have the AnimationsModule installed run: 如果没有安装AnimationsModule,请运行:

npm install @angular/animations@latest --save

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

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