-1

I know how to do an angular animation, but this time I have a component that has no specified height (it sizes based on what's inside the component). There is already content of varying height in the instances of the component. On click, it displays additional content below (i.e. "product details"), shown with an ngIf linked to a toggling variable showDetails which is a boolean.

Showing this makes the component markedly taller.

Is there a way I can animate this transition?

Steve
  • 14,401
  • 35
  • 125
  • 230

1 Answers1

1

You could remove the *ngIf and control the visibility of the content through animation alone. Try the following:

Component:

import { Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  animations: [
    trigger('displayState', [
      state('false', style({ overflow: 'hidden', height: '0px'})),
      state('true', style({ overflow: 'hidden', height: '*'})),
      transition('false => true', animate('200ms ease-in')),
      transition('true => false', animate('200ms ease-out'))
    ]),
  ]
})
export class AppComponent  {
  display = false;

  toggle() {
    this.display = !this.display;
  }
}

Template:

<button (mouseup)="toggle()">Toggle</button>
<br><br>

<div [@displayState]="display" [ngStyle]="{'background-color': '#ff000050'}">
  <p>Dynamic content</p>
  <p>that is controlled</p>
  <p>by animation alone</p>
</div>

Working example: Stackblitz

Update

You could use the existing boolean showDetails to show additional content with a transition. Again it replaces the *ngIf with only the animation. Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57
  • That's cool, but my component has variable-height content already; I am just adding _additional_ content. – Steve Mar 10 '20 at 18:56
  • I updated the question to clarify. Sorry for the confusion. – Steve Mar 10 '20 at 18:59
  • 1
    The answer could be adapted to your requirement. I've posted an update. Please check if it works for you. – ruth Mar 10 '20 at 21:43