angular animation:组件在触发动画之前被杀死



我正在尝试从管理视图的popin.component.ts中触发动画。

import { Component, EventEmitter, Input, Output } from "@angular/core";
import {
trigger,
state,
style,
animate,
transition
} from "@angular/animations";
@Component({
selector: "app-popin",
templateUrl: "./popin.component.html",
styleUrls: ["./popin.component.css"],
animations: [
trigger("openClose", [
state(
"open",
style({
transform: "translateY(0%)"
})
),
state(
"closed",
style({
transform: "translateY(100%)"
})
),
transition("* => *", animate(500))
])
]
})
export class PopinComponent {
@Input() isPopinOpen = false;
@Input() isPopinAnimationActive = false;
@Output() isPopinClosed = new EventEmitter<boolean>();
closePopin() {
this.isPopinClosed.emit(this.isPopinAnimationActive);
}
}

父组件管理布尔值来改变状态。

import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
isPopinAnimationActive: boolean;
isPopinOpen: boolean;
animate() {
this.isPopinOpen = true;
this.isPopinAnimationActive = true;
}
closeThePopin() {
this.isPopinOpen = false;
this.isPopinAnimationActive = false;
}
}

我有两个问题。

1 -当我关闭popin时,向下滑动的动画不起作用。只有当我删除注释中的行时,它才能工作。

closeThePopin() {
// this.isPopinOpen = false;
this.isPopinAnimationActive = false;
}

2 -似乎angular没有读取过渡状态"打开"one_answers"closed">

transition("open => closed", animate(500))

只有当我像这样使用*时才有效:

transition("* => *", animate(500))

下面是codesandbox代码:

https://codesandbox.io/s/lucid-wilson-lqzw2?file=/src/app/app.component.ts

你需要" play ";使用动画回调或使用:enter和:leave别名。请注意,如果你有一个*ngIfif为假,则不可能动画。

使用动画回调是改变一些你的弹出组件

<div class="container" *ngIf="isPopinOpen " (click)="isPopinAnimationActive=false">
<div class="popin" (@openClose.done)="!isPopinAnimationActive && closePopin()" 
[@openClose]="isPopinAnimationActive ? 'open': 'closed'">
content
</div>
</div>

看到click()只改变变量"isPopinAnimationActive">

In In(@openClose.done)where,如果isPopinAnimationActive=false执行函数"closePopin()"触发事件。

我用了"缩写""condition && myFunction()";如果condition为真,则执行函数,如果condition为假,则不执行函数。

使用:enter和:leave允许a *ngIf下的动画组件

在你的popin.component.html文件你使用*ngIf="isPopinOpen"来显示/隐藏div。在同一个div上,你调用closePopin()函数来处理click事件。

每次点击div时isPopinOpen变量更改为false,隐藏包含动画内容的div。

1 -当我关闭popin时,滑动的动画不起作用。只有当我删除注释中的行时,它才能工作。

滑动的动画效果很好。你无法看到动画因为一旦你点击divdiv就会隐藏因为isPopinOpen = false

要解决这个问题,你需要在app.component.ts中的closeThePopin()函数上使用setTimeout函数。popin.component.ts中的closePopin()函数文件,但不能同时在两个函数中。

我在app.component.ts中添加了setTimeOut功能文件closeThePopin()function

closeThePopin() {
// Added
setTimeout(() => {
this.isPopinOpen = false;
}, 1000);
this.isPopinAnimationActive = false;
}

工作代码示例:CodeSandBox

最新更新