How to animate a height change, without having any heights defined?

39 Views Asked by At

I have a div that contains dynamic text.

I have not set any height on the div, so its height is completely dependent on the length of the text.

With the click of a button, the text changes inside the div.

I want to have a smooth 'expand'/'collapse' animation for the height change of the div, without having to specify a fixed height.

Is it even possible for angular animations to animate height, if not specified anywhere, and just implied/computed?

I tried using the style wildcard with angular animations, but the div just jumps. The animation works fine with defined heights for the two sates.

Using :leave or :enter or height 0 is also useless here, since I want to go from height x to height y, which are both unknown and > 0.

Furthermore I tried min-height/max-height, which also didn't do much ...

TS

@Component({
  standalone: true,
  selector: 'app-animation-test',
  templateUrl: './animation.component.html',
  styleUrls: ['./animation.component.css'],
  animations: [trigger('height--expand-shrink-vertical', [
    state('collapsed', style({ height: '*', overflow: 'hidden' })),
    state('expanded', style({ height: '*', overflow: 'hidden' })),
    transition('expanded <=> collapsed', animate('200ms ease-in-out')),
    ]);
  ],
})
export class AnimationComponent implements OnInit {
  text: string;
  shortText = 'Short text';
  longText =
    'Long text Long text Long text Long text Long text Long text Long text Long text Long text Long text Long text Long text Long text Long text';

  constructor() {
    this.text = this.shortText;
  }

  ngOnInit() {}

  public toggleText(): void {
    this.text = this.text === this.shortText ? this.longText : this.shortText;
  }
}

HTML

<button (click)="toggleText()">Toggle text</button>

<div class="animated" [@height--expand-shrink-vertical]="text === shortText ? 'collapsed' : 'expanded'">
  {{text}}
</div>

Here is my Stackblitz

0

There are 0 best solutions below