I am currently working on an Angular component where I need to implement scrollIntoView functionality when the route changes. Below is a snippet of the relevant code from my component:
@ViewChild('structure') structure: ElementRef | undefined;
legacyRoute: string = '';
constructor(private apiService: ApiService, private router: ActivatedRoute, private route: Router, private cdRef: ChangeDetectorRef) { }
ngAfterViewInit() {
this.router.paramMap.subscribe(params => {
this.legacyRoute = params.get('id') || '';
console.log("checking legacy after param map subscription", this.legacyRoute);
setTimeout(() => {
if (this.legacyRoute && this.structure && this.structure.nativeElement) {
console.log("Running scrollIntoView", this.legacyRoute, this.structure, this.structure.nativeElement);
this.structure.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' });
}
}, 1000)
});
}
Issue: The scrollIntoView feature works fine when refreshing the page but encounters problems during Angular route changes. I have used a setTimeout for the function to work with a delay, but I acknowledge that this is not a reliable solution.
Attempts Made:
Eliminating the setTimeout causes scrollIntoView to malfunction during route changes.
Double-checking the validity of this.structure.nativeElement before invoking scrollIntoView.
Exploring using ngAfterViewChecked() instead of ngAfterViewInit()
Expected Outcome: I anticipate the correct execution of scrollIntoView when switching to a different route within the Angular application without relying on a setTimeout.
Additional Information:
- Angular version:
insert your angular dependencies here...
- The "structure" refers to a ViewChild or ElementRef targeting the DOM element intended for the scrollIntoView application. <-- e.g., <div #structure id="structure"> -->
My title
Given my limited experience with Angular, I seek assurance that nothing essential has been overlooked. Your guidance is highly valued, and I genuinely appreciate your time and support. Thank you in advance!