Issue
im trying to swap images using angular animations based off a 10 sec timer, but the swap never happens, ive been tinkering with it but i dont know whats wrong, the images are supposed to change when the timer hits 5 but its not working, heres some code snippets of what i tried:
TYPESCRIPT
@Component({
selector: 'app-levelone',
templateUrl: './levelone.component.html',
styleUrl: './levelone.component.css',
animations: [
trigger('fade', [
state('in', style({ 'opacity': '1' })),
state('out', style({ 'opacity': '0' })),
transition('in <=> out', [
animate(1000)
])
])
]
})
startTimer() {
this.timer = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
if (this.timeLeft<=5){
this.state = this.state === 'in' ? 'out' : 'in';
}
} else {
this.timeLeft = 10;
}
},1000)
}
HTML
<img [@fade]="state" [src]="timeLeft>5 ? '../assets/imag/img1.png' : '../assets/imag/img2.png'" />
Solution
If you check your variables "state" and "timeLeft" (in .html you write: <pre>{{timeLeft}} {{state}}</pre>
) you can check what happens.
When we work with animations we need think about the process. I imagine you want in a "tick":
- fade out the image
- change the image
- fade in the image
Well, when we want to manange animations, allow Angular control when the animation it's done. So re-thinking
<img [@fade]="state" (@fade.done)="outDone($event)" [src]="img" />
where
startTimer() {
this.timer = setInterval(() => {
if (this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 9;
}
//see that simply when 5, change the state
if (this.timeLeft == 5) {
this.state = 'out';
}
}, 1000);
}
outDone(event: any) {
//in event.fromState we get 'in'--'out'--'in'---'out'....
if (event.fromState == 'in') {
//we change the image
this.img =
this.img == '../assets/imag/img1.png'
? '../assets/imag/img2.png'
: '../assets/imag/img1.png';
//and we change the "state"
this.state = 'in';
}
}
ngOnDestroy() {
clearInterval(this.timer);
}
NOTE: Really I don't like so much the use of setInterval, better aproach is use rxjs operator timer, and subscribe unsubscribe
startTimer() {
this.subscription=timer(5000,5000).subscribe(_=>this.state='out')
}
ngOnDestroy() {
this.subscription.unsubscribe()
}
BTW: here you have another aproach
Answered By - Eliseo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.