Search code examples
angularangularjs-directiveangular-animations

Angular animation to smooth collapse/expand *ngIf content of variable height


I want to create an Angular animation that smoothly expands/collapses containers when that container's content is added/removed from the DOM.

(This is an easy CSS fix if the content never leaves the DOM, but I need to handle cases where contents are added/removed by *ngIf statements).

I have successfully got the following working:

enter image description here

https://stackblitz.com/edit/angular-x6gagz?file=src/app/components/parent/parent.component.css

The problem with the above is that the text appears before the container has expanded (notice that when clicking to expand, the bottom 'long content' appears before the container has expanded down). This causes things to overlap in my app, which doesn't look great.

I thought I could adjust the opacity so that the new contents wouldn't appear until then end, but whenever I try to change things with keyframes the height stops animating.

For example, I tried something like this:

export const experiment = trigger('grow', [
  transition('void <=> *', []),
  transition('* <=> *',[
    style({ height: '{{startHeight}}px', opacity: 0 }), 
    animate(1000, keyframes([
      style({
        opacity: 0, 
        offset: 0.8
      }),
      style({
        opacity: 1, 
        offset: 1
      }),
    ]))
  ],
    {
      params: { startHeight: 0 },
    }
  ),
]);

This makes opacity work, but the height animation stops working?


Solution

  • try adding "overflow: hidden;" in the style of the section that you want to collapse, this has fixed the problem for me, or you can try following this " https://stackblitz.com/edit/angular-animated-collapsible-block?file=src%2Fapp%2Fapp.component.html", it's an easy tutorial and it has done the job for me.