How to scroll with Router Navigation in Angular 7?

前端 未结 1 1528
醉梦人生
醉梦人生 2021-01-06 14:02

my sidebar navigation component sidebar.component.html is like this:

相关标签:
1条回答
  • 2021-01-06 14:20

    My example code is on

    1. /page1
    2. /page2
    3. /page3

    and is activated when the wheel is used to scroll down and up, it's possible to implement the same thing that I did by adding other events (like with up and down arrow key)

    In the app component, I set a window listener for wheel movement, check if the wheel is moving up or down, and last but not least navigate to the wanted route.

      constructor(
        private router: Router
      ) { }
    
      @HostListener('window:wheel', ['$event'])
      onWheelScroll(evento: WheelEvent) {
        // Scroll down
        if (evento.deltaY > 0) {
          switch (this.router.url) {
            case '/page1': {
              this.router.navigate(['/page2'])
              break
            }
            case '/page2': {
              this.router.navigate(['/page3'])
              break
            }
            case '/page3': {
              break
            }
          }
        } else { // Scroll up
          switch (this.router.url) {
            case '/page1': {
              break
            }
            case '/page2': {
              this.router.navigate(['/page1'])
              break
            }
            case '/page3': {
              this.router.navigate(['/page2'])
              break
            }
          }
        }
      }
    

    This is just one of many solutions.

    If you want that the event is emitted only if the wheel is scrolled inside the component you can do like this too:

    introduction.component.ts

      HostListener('wheel', ['$event'])
      onWheelScroll(evento: WheelEvent) {
        // Scroll up
        if (evento.deltaY > 0) {
          this.router.navigate(['experience'])
        }
      }
    

    experience.component.ts

      HostListener('wheel', ['$event'])
      onWheelScroll(evento: WheelEvent) {
        // Scroll down
        if (evento.deltaY > 0) {
          this.router.navigate(['education'])
        } else { // Scroll up
          this.router.navigate(['about'])
        }
      }
    

    education.component.ts

      HostListener('wheel', ['$event'])
      onWheelScroll(evento: WheelEvent) {
        // Scroll up
        if (evento.deltaY < 0) {
          this.router.navigate(['experience'])
        }
      }
    
    0 讨论(0)
提交回复
热议问题