从 udemy 类(class)中学习,我建立了一个“待办事项列表”, 当应用程序加载所有“任务”时,所有“任务”都是真正的动画,但是当我向 dom 添加或删除新元素时,动画不起作用,为什么?
这是我构建的 html 页面示例页面,用于在页面右侧添加任务和输出的表单 home.component.html:
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="mainTitle">My Golads List!</h1>
</div>
</div>
<div class="row">
<div class="">
<h2 class="sub-title">
My next goal is:
</h2>
<form action="">
<input type="text" name="goal" placeholder="Learn social skils" [(ngModel)]="goalText" /><br />
<input type="submit" [value]="btnText" (click)="addItem()" />
</form>
</div>
<div class="" [@goals]="goals.lenght">
<h2 class="sub-title">Goal Lists: ({{itemCount}})</h2>
<ul class="list" >
<li *ngFor="let goal of goals; let i = index" (click)="removeItem(i)">{{goal}}</li>
</ul>
</div>
</div>
这是 Angular 代码,从类(class)中学习 home.component.ts:
import { Component, OnInit } from '@angular/core';
import { trigger , style , transition , animate , keyframes , query , stagger } from "@angular/animations";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss'],
animations: [
trigger('goals' , [
transition('* => *' , [
query(':enter' , style({opacity:0}) , {optional:true}),
query(':enter' , stagger('300ms' , [
animate('.6s ease-in' , keyframes([
style({opacity:0 , transform:'translateY(-75%)' , offset:0}),
style({opacity:.5 , transform:'translateY(35px)' , offset:.3}),
style({opacity:1 , transform:'translateY(0)' , offset:1}),
]))
]) , {optional:true}),
query(':leave' , stagger('300ms' , [
animate('.6s ease-in' , keyframes([
style({opacity:1 , transform:'translateY(0)' , offset:0}),
style({opacity:.5 , transform:'translateY(35px)' , offset:.3}),
style({opacity:0 , transform:'translateY(-75%)' , offset:1}),
]))
]) , {optional:true})
])
])
]
})
export class HomeComponent implements OnInit {
itemCount: number;
btnText: string = "Add an item";
goalText: string = "my first life goal";
goals = ["my first goal", "i wnat be the world" , "buy new car"];
constructor() { }
ngOnInit() {
this.itemCount = this.goals.length;
}
addItem(){
this.goals.push(this.goalText);
this.goalText = "";
this.itemCount = this.goals.length;
}
removeItem(i){
this.goals.splice(i ,1);
}
}
最佳答案
像这样使用:
transition(':enter', [ ... ]); // void => *
transition(':leave', [ ... ]); // * => void
或者:
transition('* => void', [
style({height: '*'}),
animate('.6s ease-out' , keyframes([
style({opacity:0 , transform:'translateY(-75%)' , offset:0}),
style({opacity:.5 , transform:'translateY(35px)' , offset:.3}),
style({opacity:1 , transform:'translateY(0)' , offset:1}),
]))
]),
transition('void => *', [
style({height: '*'}),
animate('.6s ease-out' , keyframes([
style({opacity:1 , transform:'translateY(0)' , offset:0}),
style({opacity:.5 , transform:'translateY(35px)' , offset:.3}),
style({opacity:0 , transform:'translateY(-75%)' , offset:1}),
]))
]),
关于javascript - 将新元素添加到 DOM Angular 时的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576478/