1

Hello I just got a fresh issue in Angular 14 with scrolling top, after navigation to other route via <router-outlet>. I tried almost everything, below are my attempts:

appModule.ts

const routerOptions: ExtraOptions = {
  useHash: false,
  anchorScrolling: 'enabled',
  scrollPositionRestoration: 'enabled'
  // ...any other options you'd like to use
}

appComponent.ts

  ngAfterViewChecked() {
    window.scrollTo(0, 0);
  }

  onActivate(event: Event, outlet: HTMLElement) {
    window.scroll(0,0);

    console.log("Activate");
    outlet.scrollTop = 0;
    window.scroll({
      top: 0,
      left: 0,
      behavior: 'smooth'
    });

appComponent HTML:

<router-outlet (activate)="onActivate($event, outlet)" #outlet></router-outlet>

I will be grateful for each hint.

Uland Nimblehoof
  • 862
  • 17
  • 38

1 Answers1

0

Just figured it out.

Component that route is driven to:

  ngAfterViewInit(): void {
    this.commonService.scrollTo('header', BEHAVIOR.auto)
  }

Service:

  scrollTo(element: string, behavior: BEHAVIOR): void {
    (document.getElementById(element) as HTMLElement).scrollIntoView({behavior: behavior, block: "start", inline: "nearest"});
  }

Enum:

export enum BEHAVIOR {
  smooth = 'smooth',
  auto = 'auto'
}
Uland Nimblehoof
  • 862
  • 17
  • 38