简体   繁体   中英

How to trigger animation when routed to the same page with different URL parameter using Angular in Ionic 5

I was trying to to trigger the animation when the page is routed to itself with different url parameter.

For instance, for post/1 url, the animation works fine but if I route to post/2 or post/3 , the animation does not work.

I wrote the animation using Ionic Animation and calling the method everytime the route parameter changes. Could anyone please help?

Here's an excerpt from my code

HTML

<ion-icon class="custom-icon" name="chevron-back-outline"></ion-icon>

TS

constructor(private animationController: AnimationController) {
  this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
  this.animationController
    .create()
    .addElement(document.querySelector('.custom-icon'))
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}

Try to Put calling function to ionViewWillEnter()

constructor(private animationController: AnimationController) {

}

ionViewWillEnter(){
 this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
this.animationController
    .create()
    .addElement(document.querySelector('.custom-icon'))
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}

I have figured it out myself. Instead of capturing the class name using querySelector , I used ElementRef notation to make it work. Now it does work all the time when I route to any of the /post pages.

HTML

<ion-icon #leftIcon class="custom-icon" name="chevron-back-outline"></ion-icon>

TS

@ViewChild('icon1', { read: ElementRef, static: false }) leftIcon: ElementRef;

constructor(private animationController: AnimationController) {
  this.route.params.subscribe((val) => {
    this.animateIcon();
  });
}

animateIcon() {
  this.animationController
    .create()
    .addElement(this.leftIcon.nativeElement)
    .duration(1500)
    .iterations(3)
    .fromTo('transform', 'translateX(0px)', 'translateX(-80px)')
    .fromTo('opacity', '1', '0')
    .play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM