
您知道 angular 包含一个复杂的动画系统吗?当我想要在元素进入屏幕或被破坏时为其设置动画时,我发现它特别有用!
此外,您还可以使用 animationbuilder 来强制播放、暂停或停止一些自定义动画!让我们看看它是如何完成的。
在本练习中,我们首先创建一个列表,如下所示:
@component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="adduser()">add user</button>
<ul>
@for (user of users(); track user.id) {
<li>{{ user.name }}</li>
}
</ul>
`,
})
export class appcomponent {
users = signal<user[]>([
{ id: math.random(), name: 'michele' }
]);
adduser() {
this.users.update(users => [...users, { id: math.random(), name: 'new user' }]);
}
}
请注意,我们添加了一个将用户添加到列表中的按钮!
现在,如果我们想要为要添加的新用户设置动画该怎么办?首先,我们想通过在主配置中提供它来告诉 angular 我们想要使用它的动画系统:
import { provideanimationsasync } from '@angular/platform-browser/animations/async';
bootstrapapplication(appcomponent, {
providers: [
provideanimationsasync(),
]
});
然后,我们可以创建我们的动画:
import { trigger, transition, style, animate } from '@angular/animations';
const fadeinanimation = trigger('fadein', [
transition(':enter', [
style({ transform: 'scale(0.5)', opacity: 0 }),
animate(
'.3s cubic-bezier(.8, -0.6, 0.2, 1.5)',
style({ transform: 'scale(1)', opacity: 1 })
)
])
])
有了这些帮助者,我们:
更多关于如何编写动画的信息,可以参考官方指南,非常棒!
现在让我们将此动画应用到列表中的每个元素:
@component({
...,
template: `
<button (click)="adduser()">add user</button>
<ul>
@for (user of users(); track user.id) {
<li @fadein>{{ user.name }}</li> <!-- notice here -->
}
</ul>
`,
// also, add the animation to the metadata of the component
animations: [fadeinanimation]
})
现在,当添加新项目时,它会变得动画!我们的第一步已经完成。
请注意,为了让我们的动画正常工作,angular 必须跟踪 for 中的每个元素,因为否则它最终可能会在更新模板时重新创建相同的元素,从而导致不必要的结果动画。这是免费的新控制流语法,因为 track 属性是强制性的,但如果您使用旧版本的 angular 和 *ngfor 指令,则必须使用 trackby 选项,如下所示:
<li
*ngfor="let user of users; trackby: trackbyuserid"
@fadein
>{{ user.name }}</li>
// a class method in your component:
trackbyuserid(index, user: user) {
return user.id;
}
现在,让我们向列表中添加另一种类型的动画。
让我们为列表的每个元素添加一个按钮:
<li @fadein>
{{ user.name }}
<button>make me blink</button>
</li>
想象一下:我们想让元素在按下按钮时闪烁。那就太酷了!这就是 animationbuilder 服务的用武之地。
首先,让我们创建一个将应用于每个元素的指令。在此指令中,我们将注入 elementref 和 animationbuilder:
import { animationbuilder, style, animate } from '@angular/animations';
@directive({
selector: '[blink]',
exportas: 'blink', // <--- notice
standalone: true
})
export class blinkdirective {
private animationbuilder = inject(animationbuilder);
private el = inject(elementref);
}
请注意,我们导出了指令:我们将在几秒钟内找到原因。
然后,我们可以创建一个像这样的自定义动画:
export class blinkdirective {
...
private animation = this.animationbuilder.build([
style({ transform: 'scale(1)', opacity: 1 }),
animate(150, style({ transform: 'scale(1.1)', opacity: .5 })),
animate(150, style({ transform: 'scale(1)', opacity: 1 }))
]);
}
我们使用的函数与之前的动画中使用的函数相同,只是样式不同。
现在我们要创建一个播放器,它将在我们的元素上执行动画:
export class blinkdirective {
...
private player = this.animation.create(this.el.nativeelement);
}
现在让我们公开一个真正启动动画的方法!
export class blinkdirective {
...
start() {
this.player.play();
}
}
只剩下一步了:我们必须导入指令,将其应用到我们的元素,使用模板变量获取它,并在按下按钮时调用该方法!
@component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="adduser()">add user</button>
<ul>
@for (user of users(); track user.id) {
<li @fadein blink #blinkdir="blink">
{{ user.name }}
<button (click)="blinkdir.start()">make me blink</button>
</li>
}
</ul>
`,
imports: [blinkdirective],
animations: [
fadeinanimation
]
})
我们可以获取指令的实例并将其放入局部变量中,因为我们之前使用exportas导出了指令。这就是关键部分!
现在,尝试单击按钮:该元素将正确设置动画!
练习已经完成,但这只是冰山一角! animationplayer 有很多命令可用于停止、暂停和恢复动画。非常酷!
interface animationplayer {
ondone(fn: () => void): void;
onstart(fn: () => void): void;
ondestroy(fn: () => void): void;
init(): void;
hasstarted(): boolean;
play(): void;
pause(): void;
restart(): void;
finish(): void;
destroy(): void;
reset(): void;
setposition(position: number): void;
getposition(): number;
parentplayer: animationplayer;
readonly totaltime: number;
beforedestroy?: () => any;
}
如果您想使用它,这是我们的完整示例:只需将其放入 main.ts 文件中并查看它的实际效果!
import { Component, signal, Directive, ElementRef, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { trigger, transition, style, animate, AnimationBuilder } from '@angular/animations';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
interface User {
id: number;
name: string;
}
@Directive({
selector: '[blink]',
exportAs: 'blink',
standalone: true
})
export class BlinkDirective {
private animationBuilder = inject(AnimationBuilder);
private el = inject(ElementRef);
private animation = this.animationBuilder.build([
style({ transform: 'scale(1)', opacity: 1 }),
animate(150, style({ transform: 'scale(1.1)', opacity: .5 })),
animate(150, style({ transform: 'scale(1)', opacity: 1 }))
]);
private player = this.animation.create(this.el.nativeElement);
start() {
this.player.play();
}
}
const fadeInAnimation = trigger('fadeIn', [
transition(':enter', [
style({ transform: 'scale(0.5)', opacity: 0 }),
animate(
'.3s cubic-bezier(.8, -0.6, 0.2, 1.5)',
style({ transform: 'scale(1)', opacity: 1 })
)
])
])
@Component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="addUser()">Add user</button>
<ul>
@for (user of users(); track user.id) {
<li @fadeIn blink #blinkDir="blink">
{{ user.name }}
<button (click)="blinkDir.start()">Make me blink</button>
</li>
}
</ul>
`,
imports: [BlinkDirective],
animations: [
fadeInAnimation
]
})
export class App {
users = signal<User[]>([
{ id: Math.random(), name: 'Michele' }
]);
addUser() {
this.users.update(users => [...users, { id: Math.random(), name: 'New user' }]);
}
}
bootstrapApplication(App, {
providers: [
provideAnimationsAsync()
]
});
以上就是Angular LAB:动画列表并使用 AnimationBuilder 实现命令式动画的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号