【发布时间】:2021-07-13 05:14:21
【问题描述】:
这是一些工作代码:
Stackblitz:https://stackblitz.com/edit/angular-ivy-tt9vjd?file=src/app/app.component.ts
app.component.html
<button (click)='swap()'>Swap object</button>
<div @div *ngIf='object'>{{ object.data }}</div>
app.component.css
div {
width: 100px;
height: 100px;
background: purple;
display: flex;
align-items: center;
justify-content: center;
color: antiquewhite;
}
app.component.ts
import { animate, style, transition, trigger } from "@angular/animations";
import { Component } from "@angular/core";
import { interval } from "rxjs";
import { first } from "rxjs/operators";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
animations: [
trigger("div", [
transition(":enter", [
style({ transform: "scale(0)" }),
animate("250ms 0ms ease-out", style({ transform: "scale(1)" }))
]),
transition(":leave", [
style({ transform: "scale(1)" }),
animate("250ms 0ms ease-in", style({ transform: "scale(0)" }))
])
])
]
})
export class AppComponent {
object: any = { data: "DIV_1" };
swap() {
this.object = null;
interval(0)
.pipe(first())
.subscribe(() => {
this.object = { data: "DIV_2" };
});
// DESIRED CODE INSTEAD OF THE ABOVE
// this.object = { data: "DIV_2" };
}
}
此代码的问题是必须引入中间 null 状态。因此,我将演示代码与逻辑混合以“使其工作”。这违反了良好的封装实践,并为代码增加了不必要的复杂性。
如何在装饰器的 animations 属性中使用代码来获得相同的结果?
要求
- 检测对象引用的变化。
- 对对象引用更改做出反应,类似于
:enter和:leave的工作方式;首先将DIV_1动画化,然后将DIV_2动画化。 - 在
animations代码中封装有关动画的任何内容。所以交换函数应该是:swap(){this.object = { data: "DIV_2" };}
【问题讨论】:
标签: angular angular-animations