我想在每次背景改变时在我的Angular App中创建一个淡入动画,但似乎无法找到一种方法。
这是我目前的(相关)代码:
HTML:
<div @fadeIn [style.backgroundImage]="currentImage" id="home" class="pt-5">
<div class="container">
...
</div>
</div>
CSS:
#home {
background-image: url("/assets/img/friendship.jpeg");
...
}
TS:
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
animations: [
trigger('fadeIn', [
transition(':enter, :leave', [
style({ opacity: 0 }),
animate('2.5s ease-out')
])
])
]
})
export class HomeComponent implements OnInit {
private bgImgs: Array<any>;
private current: number = 0;
currentImage;
constructor(private sanitize: DomSanitizer) {
this.bgImgs = [
...
];
this.currentImage = this.bgImgs[0]
}
ngOnInit() {
Observable.interval(8669)
.subscribe(x => {
this.currentImage = this.sanitize.bypassSecurityTrustStyle(`url(${this.bgImgs[this.current]})`);
this.current == this.bgImgs.length - 1 ? (this.current = 0) : ++this.current;
})
}
我所做的基本上是通过存储在'assets'文件夹中的一系列图像进行循环,导致背景每次更改。 8s,有一个Observable。
样式动画(淡入效果)仅在我第一次进入页面时应用,而不是在更改背景时应用。据我所知,当我改变背景时,不会重新渲染页面(因此不会应用动画)。但是,我一直无法提出解决方案。
感谢您抽出宝贵时间阅读本文,我期待着您的解决方案!
答案 0 :(得分:1)
您应该使用Angular动画状态来更轻松地触发动画。因此,每次背景更改时,您都会将状态切换两次以淡出并再次淡入。
这是我创建的StackBlitz example。
<强> app.component.ts 强>
@Component({
...
animations: [
trigger('fadeIn', [
state('in', style({ 'opacity': '1' })),
state('out', style({ 'opacity': '0' })),
transition('* => *', [
animate(2000)
])
])
]
})
export class AppComponent implements OnInit {
private bgImgs: Array<any>;
private current: number = 0;
currentImage;
state = 'in';
counter = 0;
enableAnimation = false;
constructor(private sanitize: DomSanitizer) {
this.bgImgs = [...];
this.currentImage = this.bgImgs[0]
}
ngOnInit() {
Observable.interval(8669)
.subscribe(x => {
this.runAnimation();
})
}
runAnimation() {
this.enableAnimation = true;
this.counter = 0;
this.toggleState();
}
toggleImg() {
this.currentImage = this.sanitize.bypassSecurityTrustStyle(`url(${this.bgImgs[this.current]})`);
this.current == this.bgImgs.length - 1 ? (this.current = 0) : ++this.current;
}
onDone($event) {
if (this.enableAnimation) {
if (this.counter === 1) {
this.toggleImg();
}
this.toggleState();
}
}
toggleState() {
if (this.counter < 2) {
this.state = this.state === 'in' ? 'out' : 'in';
this.counter++;
}
}
}
<强> app.component.html 强>
<div [@fadeIn]="state" (@fadeIn.done)="onDone($event)" [style.backgroundImage]="currentImage" id="home" class="pt-5">
<div class="container"></div>
</div>