import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@NgModule({ imports: [BrowserAnimationsModule], ... })
@Component({
selector: 'app-my-component',
template:
,
styles: [ div { width: 100px; height: 100px; background: red; } .state1 { background: blue; } .state2 { background: green; }
],
animations: [
trigger('myAnimation', [
state('state1', style({
background: 'blue'
})),
state('state2', style({
background: 'green'
})),
transition('state1 <=> state2', animate('500ms ease-out'))
])
]
})
export class MyComponent {
state = 'state1';
toggleState() { this.state = this.state === 'state1' ? 'state2' : 'state1'; } }
在这个示例中,我们定义了一个包含三个动画状态(默认状态、state1和state2)的动画。我们在组件中维护了当前状态,并在点击事件中切换状态。当我们切换状态时,Angular会自动应用定义的过渡动画。