0
votes

I am trying to achieve a simple animation with angular. On the click of the button I change the state of showState from to shown. Since I am using *ngIf I have used void keyword in the animation and yet it is not working.

STACKBLITZ

CSS

p {
  border: 1px solid black;
  background-color: lightblue;
  padding: 10px;
}

app.component.ts

import { showStateTrigger } from './animations';
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"],
  animations: [
    showStateTrigger
  ]
})
export class AppComponent {
  isShown = false;
}

HTML

<button (click)="isShown = !isShown">Toggle Element</button>
<p [@showState]="isShown ? 'shown' : 'notShown'" *ngIf="isShown"> You can see me now!</p>

Animations.ts

import { state, style, transition, trigger, animate } from "@angular/animations";

export const showStateTrigger = trigger("showState", [

  transition('void => shown', [
    style({
      opacity: 0
    }),
    animate(2000, style({
      opacity: 1
    }))
  ])

]);
2

2 Answers

2
votes

So, I figured it out myself. I was missing :

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

in appModule.ts

It is strange that angular doesn't complain about it. No errors. No Warnings.

0
votes

You shouldn't use both [@showState]="isShown ? 'shown' : 'notShown'" and *ngIf="isShown at the same time. especially when notWhosn isn't a registered state.

Your code should look as follows:

@Component({
  selector: 'app-root',
  template: `
     <button (click)="isShown = !isShown">Toggle Element</button>
     <p @enterAnimation *ngIf="isShown"> You can see me now!</p>`
  ,
  animations: [
    trigger(
      'enterAnimation', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('500ms', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        style({ opacity: 1 }),
        animate('500ms', style({ opacity: 0 }))
      ])
    ]
    )
  ],
})
export class AppComponent {
  isShown = false;
}