动画不保持最终状态,切换回原始状态

SHR*_*HRX 2 angular angular-animations

我目前正在学习 Angular 6,但遇到了一些问题。我正在使用本教程:https : //www.yearofmoo.com/2017/06/new-wave-of-animation-features.html

当我单击按钮时,动画按预期触发,但在淡出后文本再次弹出。任何想法为什么它会切换回原始状态?

在此处输入图片说明

提前致谢

应用程序组件.html

<button (click)="toggle()">Toggle Fade</button>
<div [@someCoolAnimation]="bindingVar">hello there</div>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';
import {trigger, transition, style, animate} from "@angular/animations";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('someCoolAnimation', [
      transition('* => fadeIn', [
        style({ opacity: 0 }),
        animate(1000, style({ opacity: 1 }))
      ]),
      transition('* => fadeOut', [
        animate(1000, style({ opacity: 0 }))
      ])
    ])
  ]
})
export class AppComponent {
  bindingVar = '';
  fadeIn() {
    this.bindingVar = 'fadeIn';
  }
  fadeOut() {
    this.bindingVar = 'fadeOut';
  }
  toggle() {
    this.bindingVar == 'fadeOut' ? this.fadeIn() : this.fadeOut();
  }
}
Run Code Online (Sandbox Code Playgroud)

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

小智 5

You are looking for state from angular animations. It will enforce styles when the animation is in a given state. You can see the official example here https://angular.io/guide/animations#transitioning-between-two-states

Make sure you import the state

import { ... state } from '@angular/animations';
Run Code Online (Sandbox Code Playgroud)

State is used like this

animations: [
    trigger('someCoolAnimation', [
      state('fadeIn'
      //enforce your styles for the fadeIn state here
          style({ opacity: 1 })
      ),
      state('fadeOut'
      //enforce your styles for fadeOut state here
          style({ opacity: 0 })
      )
      transition('* => fadeIn', [
        animate(1000)
      ]),
      transition('* => fadeOut', [
        animate(1000)
      ])
    ])
  ]
Run Code Online (Sandbox Code Playgroud)