我有一个应用程序,每30秒显示一次随机报价。我想使用角度动画为这些引号设置动画。我面临的问题是仅首先对文本进行动画处理(首次加载页面时)。但是,每次引用更改时,它都应该动画。
这是我已经尝试过的代码
import {Component, OnInit} from '@angular/core';
import {QuoteService} from '../services/quote.service';
import {animate, state, style, transition, trigger} from '@angular/animations';
@Component({
selector: 'app-quote-item',
templateUrl: './quote-item.component.html',
styleUrls: ['./quote-item.component.css'],
animations: [
trigger('changeQuote', [
state('true', style({
opacity: '1'
})),
state('false', style({
opacity: '0'
})),
transition('0 <=> 1', animate('1000ms ease'))
])
]
})
export class QuoteItemComponent implements OnInit {
changeQuote = true;
quote = {};
constructor(private service: QuoteService) { }
ngOnInit() {
this.getQuote();
setInterval(this.getQuote, 30000);
}
getQuote = () => {
this.changeQuote = false;
this.service.getRandomQuote().subscribe( quote => {
this.quote = quote;
this.changeQuote = true;
});
}
}
HTML代码:
<div [@changeQuote]="changeQuote" class="container">
<div class="row">
<div class="col quote my-auto">
<div class="text-center">
<p class="text" [innerText]="quote['quote']"></p>
</div>
<div class="text-right" style="margin-right: 25px">
<p style="font-weight: bold; font-size: 38px;" [innerText]="quote['author']"></p>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
以下是动画的一个有效示例:quote-animation该示例仅使用setInterval更改动画的状态。
主要问题是您在getQuote()中进行订阅:
答案 1 :(得分:0)
问题在于@angular的更改检测未从true => false => true捕获切换(更改是在更改检测器有机会做任何事情之前进行的)。如果您延迟服务订阅,则会看到动画:
getQuote = () => {
this.service.getRandomQuote().pipe(
tap(_ => this.changeQuote = false),
delay(1000)).subscribe(quote => {
this.quote = quote;
this.changeQuote = true;
});
}
观看此演示:Stackblitz