angular - 如何使用 Angular 12 中的动画为 :leave 事件上的 :host 元素设置动画?
问题描述
我们有一个非常简单的组件,应该淡入淡出:enter
和:leave
事件:
import { Component, HostBinding } from '@angular/core';
import { animate, style, transition, trigger } from '@angular/animations';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
animations: [
trigger('host', [
transition(':enter', [
style({ opacity: 0 }),
animate('240ms linear', style({ opacity: 1 })),
]),
transition(':leave', [
style({ opacity: 1 }),
animate('240ms linear', style({ opacity: 0 })),
])
]),
]
})
export class TestComponent {
@HostBinding('@host') host() {
return true;
}
}
该组件的使用方式如下:
<app-test *ngIf="someBoolean"></app-test>
现在动画:enter
确实运行了。但是当组件被移除时,元素不会淡出(变量someBoolean
变为false
)。
什么不见了?
解决方案
在父组件中使用*ngIf
使元素动画不被注册
让我们看看会发生什么
someBoolean
=> 从false
<app-test *ngIf='someBoolean'></app-test>
不存在someBoolean
=>true
- 加载
<app-test></app-test>
- 加载动画;……等一下,刚刚发生了什么?我们加载
app-test
然后加载动画!但是在什么时候触发动画呢?这个问题的答案是为什么你的动画没有被触发。我们需要先申请动画,然后才能应用它们
所以让我们停止上述事件序列并重试这些步骤
someBoolean
=> 从false
<app-test [shown]='someBoolean'></app-test>
创建- 注册动画
someBoolean
=>true
- 显示内容
<app-test></app-test>
- 动画在他们注册后开始!
好的,现在我们已经了解了它的工作原理,让我们开始编写代码
组件使用
`<app-test [shown]='someBoolean'></app-test>`
组件 TS 文件
@Component({
selector: "app-test",
templateUrl: "./test.component.html",
styleUrls: ["./test.component.css"],
animations: [
trigger("host", [
transition(":enter", [
style({ opacity: 0 }),
animate("240ms linear", style({ opacity: 1 }))
]),
transition(":leave", [
style({ opacity: 1 }),
animate("240ms linear", style({ opacity: 0 }))
])
])
]
})
export class TestComponent implements OnInit {
// @HostBinding("@host") host() {
// return true;
// }
@Input() shown;
constructor() {}
ngOnInit() {}
}
我已经注释掉了,@HostBinding
因为我没有看到它是如何在这里实现的。
最后我们可以*ngIf
在组件的内容中应用
<div *ngIf='shown'>
<!-- Animation works! -->
</div>
推荐阅读
- wordpress - 来自 SantuCommerce 插件的 iframe 打开时 WordPress 主题损坏
- apache-spark - 什么决定了 Spark 中一个操作的映射器和缩减器的数量
- sql - 累积和值 1 遇到 0 SQL 时重置和
- arraylist - 在 JAVA 中 nCopies API 的定义中不变性是什么意思?这个 API 的用例是什么?
- java - 为什么 GMT 和 UTC 时区没有相同的规则
- firebase - Firebase 函数 - 从未捕获的无效引用中获取价值
- exchange-server - 本地交换的 Outlook Web 加载项身份验证失败
- java - 强制开发人员为其添加的所有 UI 元素设置可访问性
- python - 基于行的坐标排序列表
- ios - AVPlayer 无法播放 Live Radio URL