Angular 4编程动画



如何编程添加动画?

@Component({
    moduleId: module.id,
    selector: 'my-toolbar',
    templateUrl: './my-toolbar.component.html',
    styleUrls: ['./my-toolbar.component.scss'],
    encapsulation: ViewEncapsulation.None,
    animations: [
        trigger('myToolbarState', [
            state('initial', style({top: '*'})),
            state('up', style({top: '-50px')),
            transition('initial => up, up => initial',
                animate(HEADER_SHRINK_TRANSITION))
        ])
    ]
})

如何在没有注释的情况下实现同样的事情?我的基本目标是创建一个动态触发函数,该功能使用基于某些@Input的不同值。

重要的是要注意,动画或触发器必须具有至少一个变量。这使这个问题与我如何重用动画不同。

我结束了以下工厂类,如下所示,用于animations[]: -

这是如下:

@Component({
  selector: 'my-app-header',
  moduleId: module.id,
  templateUrl: './app-header.component.html',
  styleUrls: ['./app-header.component.scss'],
  animations: [
      MyToolbarAnimator.createTrigger('appHeaderState', '50px', '0')
  ]
})

使用静态方法createTrigger定义的MyToolbarAnimator,该方法返回AnimationTriggerMetadata,如下所示

mytoolbaranimator

import {trigger, state, style, animate, transition, AnimationTriggerMetadata} from '@angular/animations';
export const HEADER_SHRINK_TRANSITION = '250ms cubic-bezier(0.4,0.0,0.2,1)';
export class MyToolbarAnimator {
    static createTrigger(triggerName: string, initialTop: string, upTop: string): AnimationTriggerMetadata {
        return trigger(triggerName, [
            state('initial', style({top: initialTop})),
            state('up', style({top: upTop})),
            transition('initial => up, up => initial',
                animate(HEADER_SHRINK_TRANSITION))
        ]);
    }
}

更新:

或您的动画参数非常动态,并且基于组件行为的更改https://angular.io/api/animation/animationbuilder#usage-notes这个

// import the service from BrowserAnimationsModule
import {AnimationBuilder} from '@angular/animations';
// require the service as a dependency
class MyCmp {
  width = 100;
  constructor(private _builder: AnimationBuilder) {}
  changeWidth(aWidth:number) {
      this.width = aWidth;
  }
  makeAnimation(element: any) {
    // first define a reusable animation
    const myAnimation = this._builder.build([
      style({ width: 0 }),
      animate(1000, style({ width: `${this.width}px` }))
    ]);
    // use the returned factory object to create a player
    const player = myAnimation.create(element);
    player.play();
  }
}

最新更新