[英]Angular Animation: animate only added item in ngFor list
我在ngFor
有一個數組項列表。 我有一個簡單的按鈕,可以向數組中添加一個項目。 我想僅在添加項目時將動畫應用於項目,但盡管這有效,但頁面上已有的列表項目組在頁面加載時獲得動畫。 如何將動畫僅限於新添加的項目? 這是在 Angular 10 中。
我做了一個精簡的 Stackblitz 。
animations: [
trigger("myTrigger", [
state(
"fadeInFlash",
style({
opacity: "1"
})
),
transition("void => *", [
style({ opacity: "0", transform: "translateY(20px)" }),
animate("500ms")
])
])
]
<p>
<button (click)="addItem()">Add Item</button>
</p>
<ul>
<li *ngFor="let item of items" [@myTrigger]='state'>{{item}}</li>
</ul>
這是 stackbliz 到您的問題的解決方案鏈接,我剛剛使用了 Angular 動畫的禁用屬性。 如果標志變量為真,則動畫將被禁用,如果為假,則動畫將被啟用,這是我們在頁面初始化后所有內容加載后所做的,這樣動畫的觸發器將僅適用於推送操作。
編輯:為避免控制台錯誤ExpressionChangedAfterItHasBeenCheckedError
請在添加項目上啟用動畫,如下所示。 甚至 stackbliz 代碼也已相應更新以供參考。
addItem() {
if (this.flag) {
// Enabling Animation
this.flag = !this.flag;
}
this.items.push("another item");
}
app.component.ts
import { Component } from "@angular/core";
import {
animate,
animateChild,
group,
query,
style,
transition,
trigger,
state
} from "@angular/animations";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
animations: [
trigger("myTrigger", [
state(
"fadeInFlash",
style({
opacity: "1"
})
),
transition("void => *", [
style({ opacity: "0", transform: "translateY(20px)" }),
animate("500ms")
])
])
]
})
export class AppComponent {
flag: boolean = true;
items = ["item 1", "item 2", "item 3"];
state: string = "fadeInFlash";
addItem() {
if (this.flag) {
this.flag = !this.flag;
}
this.items.push("another item");
}
}
應用程序組件.html
<p>
Start editing to see some magic happen :)
</p>
<p>
<button (click)="addItem()">Add Item</button>
</p>
<ul>
<li *ngFor="let item of items" [@.disabled]="flag" [@myTrigger]='state'>
{{item}}</li>
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.