How to animate :enter & :leave transitions conditionally in Angular?

akcasoy picture akcasoy · Feb 25, 2019 · Viewed 8.9k times · Source

I have a list, where the items have an animation like this:

<li @animation>

And this is my animation trigger:

trigger('animation', [
  transition(':enter', [
    style({ height: '0px', 'padding-top': '0', 'padding-bottom': '0'}),  // initial
    animate('0.5s',
      style({ height: '*', 'padding-top': '*', 'padding-bottom': '*'}))  // final
  ]),
  transition(':leave', [
    style({ height: '*', 'padding-top': '*', 'padding-bottom': '*', opacity: 1}),  // initial
    animate('0.5s',
      style({ height: '0px', 'padding-top': '0', 'padding-bottom': '0', opacity: 0}))  // final
  ])
])

How can i conditionally turn on/off this animation for a specific item? Actually i look for sth. like this:

<li [@animation]=item.isAnimated>

which does not work at all.

And unfortunately Angular documentation has just a sentence about this:

For elements entering or leaving a page (inserted or removed from the DOM), you can make the animations conditional. For example, use *ngIf with the animation trigger in the HTML template.

But when i combine the animation annotation with a *ngIf, the not-animated items will obviously not be shown at all:

<li *ngIf="item.isAnimated" @animation>

I want to show all the items further on regardless of isAnimated flag. I just want to turn on/off the animation for a specific item.

Answer

j4rey picture j4rey · Feb 25, 2019

According to Angular IO:

When true, the special animation control binding @.disabled binding prevents all animations from rendering. Place the @.disabled binding on an element to disable animations on the element itself, as well as any inner animation triggers within the element.

The following example shows how to use this feature:

@Component({
    selector: 'my-component',
    template: `
    <div [@.disabled]="isDisabled">
        <div [@childAnimation]="exp"></div>
    </div>
    `,
    animations: [
        trigger("childAnimation", [
            // ...
        ])
    ]
})
class MyComponent {
      isDisabled = true;
  exp = '...';
}

When @.disabled is true, it prevents the @childAnimation trigger from animating, along with any inner animations.