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

时间:2018-08-24 08:54:09

标签: angular angular-animations

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

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

enter image description here

预先感谢

app.component.html

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

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();
  }
}

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 { }

2 个答案:

答案 0 :(得分:2)

您正在从角度动画中寻找state。当动画处于给定状态时,它将强制执行样式。您可以在此处https://angular.io/guide/animations#transitioning-between-two-states

查看官方示例

确保您导入状态

import { ... state } from '@angular/animations';

状态是这样使用的

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)
      ])
    ])
  ]

答案 1 :(得分:1)

我的问题是由于在需要该值的一端设置了不带px的值引起的。

此BREAKS -在动画之后将边距重置为其初始值:

state('open', style({
    marginLeft: '-100'
}))

这很有效!

state('open', style({
    marginLeft: '-100px'
}))