Angular animations without ngIf

Viewed 187

I am trying to switch from CSS animation to Angular Animations and I can't find out how to animate an element from an array without displaying all and show only the selected one with a *ngIf.

Animations are defined in the TS file as follow:

@Component({
  ...
  animations: [
    trigger("carouselAnimation", [
      // Next
      transition(":increment", [
        query(":enter", [
          style({ opacity: 0, transform: "translateX(100%)" }),
          animate(".3s", style({ opacity: 1, transform: "translateX(0)" }))
        ])
      ]),
      // Previous
      transition(":decrement", [
        query(":enter", [
          style({ opacity: 0, transform: "translateX(-100%)" }),
          animate(".3s", style({ opacity: 1, transform: "translateX(0%)" }))
        ])
      ])
    ])
  ]
})

and in HTML, the selected image is displayed as follow:

<div [@carouselAnimation]="counter">
    <ng-container *ngFor="let img of images; let i=index">
        <img [src]="img" style="height:200px; width:200px" *ngIf="i===counter"/>
    </ng-container>
</div>

All works fine so far, but what I'm trying to do is animate the image without displaying all the others, and use a *ngIf to hide them and keep only the selected one:

<div [@carouselAnimation]="counter">
    <img [src]="imgSrc" style="height:200px; width:200px">
</div>

But if I'm doing this, the animation is not working anymore.

I have also created a demo in Stackblitz.

1 Answers

The thing you should do is ditch the ngFor and instaead use the image like so:

<img [@carouselAnimation]="counter" [src]="images[counter]" style="height:200px; width:200px" />

The other thing that you should do with this approach is to change the query from :enter to :self in order to trigger the animation over the <img/> element

Here is a StackBlitz with working demo (forked from you solution).

The only issue with this approach (that is also an issue with you *ngFor solution) is that if the image loads slower than the animation the user will end up with a buggy experience.

Related