【发布时间】:2018-09-16 05:55:36
【问题描述】:
使用 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';
}
}
调用模板:
<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>
【问题讨论】:
-
如果您能帮到您,您可以提出 plunker。
-
我用 plnkr 编辑了我的帖子
标签: javascript animation typescript angular