具有可变样式的angular2动画

nog*_*ade 10 javascript animation typescript angular

使用Typescript和Angular 2.0.0-rc.4

如何从模板中指定样式属性值,以便我可以重复使用按钮?例如,如果我想根据模板绑定的某个属性为每个按钮指定不同的背景颜色.见下文

假设以下组件:

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

@Component({
  selector: 'my-toggle-button',
  template: `<div @state="state" (click)="click()">{{bgColor}}</div>`,
  animations: [
    trigger('state', [
      state('inactive', style({
        'color': '#606060'
      })),
      state('active', style({
        'color': '#fff',
        'background-color': '#606060' // I want this to be bgColor
      })),
      transition('inactive <=> active', animate('100ms ease-out'))
    ])
  ]
})

export class ToggleButtonComponent implements OnInit {
  @Input() bgColor: string;
  state: string = 'inactive';
  active: boolean = false;

  ngOnInit() {
    this.state = this.active ? 'active' : 'inactive';
  }

  click() {
    this.active = !this.active;
    this.state = this.active ? 'active' : 'inactive';
  }
}
Run Code Online (Sandbox Code Playgroud)

调用模板:

<h1>Animated Directive</h1>
<my-toggle-button [bgColor]="'#f00'"></my-toggle-button>
<my-toggle-button [bgColor]="'#0f0'"></my-toggle-button>
<my-toggle-button [bgColor]="'#00f'"></my-toggle-button>
Run Code Online (Sandbox Code Playgroud)

http://plnkr.co/edit/KBO2pgS8B0lSAPLIf0Js?p=preview

Shl*_*saf 9

根据这个问题的标题,我假设你想将表达式绑定到动画配置.

如果值来自内联模板表达式或来自组件类的属性绑定,则无关紧要.

在RC4中,这是不可能的,动画模块/引擎支持静态/常量定义.我使用术语定义而不是样式,因为这样的绑定可以用于样式以及关键帧,过渡,动画和基本上所有动画元数据工厂.

您应该期望这个功能出现在下一个版本的角度之一,无法告诉它什么时候应该来.将动画元数据设置为引用变量而不是常量是超级强大的并且基本上是强制性的,因为它是可重用动画的基本要求.

具有可重复使用的动画将引领更广泛的社区采用动画模块的方式.在角度1中,它是内置的,因为动画模块使用全局定义的CSS类来启动动画,因此CSS类用于可重用部分.

在角度2中,由于很多原因(封装,自己的CSS解析器,没有绑定到CSS的动画引擎等等),方法是不同的.

可重复使用的动画将为动画的完整第三方库铺平道路,想想animation.cssng-fx,但作为一组角度指令/模块.

大约3周前,我在角度回购上打开了一个问题,请求此功能.动画的主要开发者已经确认它即将到来,所以紧紧抓住:)