文本更改不起作用时的角度淡入/淡出



我目前正在尝试在Angular中构建一个单词转盘。这个想法是有一个包含x个元素的数组,这些元素每隔3秒就会随着渐变而变化,这样看起来就不会很硬。问题是,我只是设法在初始页面加载时显示渐变动画,但不是在每个单词更改时都显示。

这是我的动画:

animations : [
trigger('fadeAnimation', [
state('in', style({opacity: 1})),
transition(':enter', [
style({opacity: 0}),
animate(600)
]),
transition(':leave',
animate(600, style({opacity: 0})))
])
]

这是我的HTML元素:

<span *ngIf="wordCarousel" id="word-carousel"
#wordCarousel [@fadeAnimation]="'in'">{{wordCarousel[0]}}</span>

这就是我更改单词的地方:

@ViewChild('wordCarousel', {static: false}) wordCarouselEl: ElementRef;
wordCarousel = [
'Hallo',
'Hello',
'Servus'
];
wordCounter = 1;
ngAfterViewInit() {
if (this.wordCarousel) {
setInterval(() => {
this.wordCarouselEl.nativeElement.innerHTML = this.wordCarousel[this.wordCounter];
this.wordCounter++;
if (this.wordCounter >= this.wordCarousel.length) {
this.wordCounter = 0;
}
}, 3000);
}

您可以在这里找到一个工作示例:https://angular-ivy-gsunum.stackblitz.io

谢谢你帮我找到问题。

Jo,我更喜欢使用(animation.done)来控制动画何时完成。所以我不能使用:enter:leave。如果你在SO建议和堆栈中看到我的答案,你有两个动画,一个使用两个div,另一个只使用一个。

想象一下:

animations: [
trigger("fadeAnimation", [
transition("false=>true", [
style({ opacity: 0 }), //At begin animation, opacity=0
animate("2500ms", style({ opacity: 1 }))  //the animation makes opacity=0 to opacity=1
]),
//the animate("2500ms 2000ms" means that the animation spend 2500ms, 
//but start after 2000ms. So opacity=1 2000ms, then goes to 0 in 2500ms
transition("true=>false", [
//here don't use a "initial style", simply makes opacity goes to 0
animate("2500ms 2000ms", style({ opacity: 0 }))])
])
]

查看值是如何为假和为真的,并且无需在中定义状态

你的.html赞:

<span  id="word-carousel"
[@fadeAnimation]="toogle" (@fadeAnimation.done)="nextWord($event)">
{{wordCarousel[wordCounter]}}
</span>

看到CCD_ 4等于"0";变量";,如果我们把变量从true改为false,从false改为true,动画就会产生,所以

toogle:boolean=true;  //declare the variable "toogle"
ngAfterViewInit() { //in ngAfterViewInits "begins" the animation
//see that we use a setTimeout, we want that Angular
//"paint" the elements and, after, change the variable
setTimeout(()=>{
this.toogle=false;
})
}

下一个单词的功能

nextWord(event: any) {
//we change the toogle
this.toogle = !this.toogle;
//if event.fromState (the value of the animation) is true (when pass from true to false)
if (event.fromState)
this.wordCounter = (this.wordCounter + 1) % this.wordCarousel.length;
}

堆叠式

最新更新