Angular Animation For Dynamically Changing Height

后端 未结 4 1174
日久生厌
日久生厌 2020-12-14 02:56

I\'ve successfully gotten a panel to animate expanding and closing when entering and leaving the DOM. The problem is I now have a busy indicator inside the panel prior to sh

4条回答
  •  一整个雨季
    2020-12-14 03:54

    I made a directive based on @MartinCremer answer. I think using a directive makes more sense since by doing that, you also should add the animation to your parent component (and it's close the standard way of adding animations).

    So inside my animations.ts file. I've added the animation:

    export const smoothHeight = trigger('grow', [
      transition('void <=> *', []),
      transition('* <=> *', [style({ height: '{{startHeight}}px', opacity: 0 }), animate('.5s ease')], {
        params: { startHeight: 0 }
      })
    ]);
    

    then you should add this animation to your parent component (the component that you want to use the animation inside it):

    import { smoothHeight } from '@app/animations';
    @Component({
      selector: 'app-parent',
      templateUrl: './parent.component.html',
      styleUrls: ['./parent.component.scss'],
      animations: [smoothHeight]
    })
    

    And here is the directive which is really close to the component of @MartinCremer:

    import { Directive, OnChanges, Input, HostBinding, ElementRef } from '@angular/core';
    
    @Directive({
      selector: '[smoothHeight]',
      host: { '[style.display]': '"block"', '[style.overflow]': '"hidden"' }
    })
    export class SmoothHeightAnimDirective implements OnChanges {
      @Input()
      smoothHeight;
      pulse: boolean;
      startHeight: number;
    
      constructor(private element: ElementRef) {}
    
      @HostBinding('@grow')
      get grow() {
        return { value: this.pulse, params: { startHeight: this.startHeight } };
      }
    
      setStartHeight() {
        this.startHeight = this.element.nativeElement.clientHeight;
      }
    
      ngOnChanges(changes) {
        this.setStartHeight();
        this.pulse = !this.pulse;
      }
    }
    

    Finally inside parent.component.html use the directive:

    // any html content goes here

    Just replace yourAnimationIndicator with the variable that the animation should trigger on change of its value.

提交回复
热议问题