模型更改时Angular2动画

时间:2016-11-23 15:06:57

标签: angular angular2-components angular2-animation

我有组件PageComponent,其数据在不同的网址上更新。我希望在更改Page模型时进行动画制作。在我给定的示例动画中,仅在加载PageComponent时才第一次工作。

当模型更新时,我应该添加/更改该动画的作用?

page.component.ts

@Component({
    selector: 'my-page',
    templateUrl: './page.component.html',
    styleUrls: ['./page.component.scss'],
    providers: [PageService],
    pipes: [SafePipe],
    host: { '[@routeAnimation]': 'true' },
    animations: Animations.page
})
export class PageComponent implements OnInit {

    page: Page;

    constructor(private route: ActivatedRoute,
                private pageService: PageService) {
    }

    ngOnInit() {
        this.route.params.forEach((params: Params) => {
            let uri = params['uri'];
            this.getPage(uri);
        });
    }

    getPage(uri: string) {
        this.pageService.getPage(uri).subscribe(
            page => this.page = page,
            error => this.errorMessage = <any>error
        );
    }
}

animation.ts

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

export class Animations {
    static page = [
        trigger('routeAnimation', [
            transition('void => *', [
                style({
                    opacity: 0,
                    transform: 'translateX(-100%)'
                }),
                animate('2s ease-in')
            ]),
            transition('* => void', [
                animate('2s 10 ease-out', style({
                    opacity: 0,
                    transform: 'translateX(100%)'
                }))
            ])
        ])
    ];
}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,我使用文章Using ChangeDetection With Animation To Setup Dynamic Void Transitions In Angular 2 RC 6中描述的步骤解决了这个问题。您基本上需要执行3个步骤:

  1. 导入 ChangeDetectorRef

    import { ChangeDetectorRef } from "@angular/core";
    
  2. 使用依赖注入

    创建此类的实例
    constructor(private changeDetector: ChangeDetectorRef) {}
    
  3. 更改后,在 ChangeDetectorRef 类的实例上调用方法 detectChanges()

    // Change your model ...
    SomeMethodWhichChangesTheModel();
    
    // ... and call the detectChanges() method on the ChangeDetectorRef
    this.changeDetector.detectChanges();