0

I am creating a component based on a condition:

<div *ngIf="showContainer" class="container">

And now I want to add some animation to it, meaning I want to blend in the container instead of having it just pop up. I was thinking about the following:

<div *ngIf="showContainer" class="container" [ngClass]="{'show': showContainer, 'hide': !showContainer}">

And then in my SCSS file, I am adding the following:

.container {
   transition: opacity 3s linear;
      
   &.show {
     opacity: 1;
   }
    
   &.hide {
     opacity: 0;
   }
}

Now, this animation does not work at all. I am toggling the showContainer variable on clicking an icon and I have verified that the variable is actually being toggled! I have a feeling this might be connected to the *ngIf directive. Can somebody help me out?

Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78
Luk
  • 1,009
  • 2
  • 15
  • 33
  • 1
    Maybe remove the `ngIf` and see how that goes. – Octavian Mărculescu May 03 '22 at 06:55
  • If showComtainer is false, by the *ngIf there is no div to have class 'hide' – Turo May 03 '22 at 07:12
  • Might be related to https://stackoverflow.com/questions/64707211/transition-not-working-correctly-when-element-is-added-to-the-dom. – Christian May 03 '22 at 08:16
  • works like a charm without the `ngIf`. However, I would rather have the `ngIf`, since I might have multiple components, i.e. multiple containers on one page. The `ngIf` ensures that a container is only rendered when clicking on a toggle-button for a specific container. I wouldn't like to clutter my page with multiple hidden containers. Is it possible to animate the creation of a component? I checked out the following question, but this doesn't seem to work either: https://stackoverflow.com/questions/36417931/angular-2-ngif-and-css-transition-animation – Luk May 03 '22 at 12:34

1 Answers1

0

please, try to use the class as follow.

Proper way

<div *ngIf="showContainer" class="container"
  [class.show]="showContainer"
  [class.hide]="!showContainer"
>

Cannot tell you the reason why this isn't working, seems to be good to me. But what I could experience is that, if you're already using a class the [ngClass] wont be taking in account, since it's the same attribute.

Other way: ngClass

Remove the class="container" an put it into the ngClass with a default true value.

<div *ngIf="showContainer" [ngClass]="{'container': true, 'show': showContainer, 'hide': !showContainer}">
Raphaël Balet
  • 6,334
  • 6
  • 41
  • 78