3

I'm learning Angular 6 at the moment and ran into a bit of a problem. I'm using this tutorial: https://www.yearofmoo.com/2017/06/new-wave-of-animation-features.html

When i click the button, the animation triggers as expected, but after the fade out the text pops up back again. Any ideas why it switches back to the original state?

enter image description here

Thanks in advance

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 { }
SHRX
  • 559
  • 1
  • 6
  • 17

2 Answers2

6

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';

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)
      ])
    ])
  ]
lietutis
  • 201
  • 1
  • 12
Shannon
  • 884
  • 8
  • 15
-1

My issue was caused by setting a value without px on the end that requires it.

This BREAKS - resets the margin its initial value after the animation:

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

This WORKS!!!

state('open', style({
    marginLeft: '-100px'
}))
Tom Benyon
  • 971
  • 10
  • 15