Angular 基于组件中条件内容的动画
Angular animation based on conditional content in component
我知道如何制作 angular 动画,但这次我有一个没有指定高度的组件(它的大小取决于组件内部的内容)。组件的实例中已经有不同高度的内容。单击时,它会在下方显示其他内容(即 "product details"),显示为 ngIf
链接到切换变量 showDetails
,这是一个布尔值。
显示此内容会使组件显着变高。
有什么方法可以让这个过渡动画化吗?
您可以删除 *ngIf
并仅通过动画控制内容的可见性。请尝试以下操作:
组件:
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;
}
}
模板:
<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>
工作示例:Stackblitz
更新
您可以使用现有的布尔值 showDetails
来显示带有过渡的附加内容。它再次仅用动画替换了 *ngIf
。工作示例:Stackblitz
我知道如何制作 angular 动画,但这次我有一个没有指定高度的组件(它的大小取决于组件内部的内容)。组件的实例中已经有不同高度的内容。单击时,它会在下方显示其他内容(即 "product details"),显示为 ngIf
链接到切换变量 showDetails
,这是一个布尔值。
显示此内容会使组件显着变高。
有什么方法可以让这个过渡动画化吗?
您可以删除 *ngIf
并仅通过动画控制内容的可见性。请尝试以下操作:
组件:
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;
}
}
模板:
<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>
工作示例:Stackblitz
更新
您可以使用现有的布尔值 showDetails
来显示带有过渡的附加内容。它再次仅用动画替换了 *ngIf
。工作示例:Stackblitz