我根据@MartinCremer 的回答做了一个指令。我认为使用指令更有意义,因为这样做,您还应该将动画添加到您的父组件(并且它接近添加动画的标准方式)。
所以在我的animations.ts 文件中。我已经添加了动画:
export const smoothHeight = trigger('grow', [
transition('void <=> *', []),
transition('* <=> *', [style({ height: '{{startHeight}}px', opacity: 0 }), animate('.5s ease')], {
params: { startHeight: 0 }
})
]);
那么您应该将此动画添加到您的父组件(您要在其中使用动画的组件):
import { smoothHeight } from '@app/animations';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss'],
animations: [smoothHeight]
})
这是与@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;
}
}
最后在parent.component.html里面使用指令:
<div [smoothHeight]="yourAnimationIndicator">
// any html content goes here
</div>
只需将yourAnimationIndicator 替换为动画应在其值更改时触发的变量。