简体   繁体   中英

Angular 2 animation with property binding not working

I'm trying to make a fade in animation to 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'. The toggle event is not working and other click events in the code do not react. When I remove the 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:

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

You also have to import BrowserAnimationsModule. So for example in your AppModule:

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

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

If you don't have the AnimationsModule installed run:

npm install @angular/animations@latest --save

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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