Troubleshooting Angular: Implementing scrollIntoView on route change without using setTimeout within ngAfterViewInit

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!

Answer №1

One possible approach is to listen for the router navigation ends event to ensure that the navigation process is complete, along with an effect for handling signals.

This method should also work for the initial call. You could try something similar to the code below:

private readonly navigationEnd = toSignal(
  this.router.events.pipe(filter((event): event is NavigationEnd => event instanceof NavigationEnd))
)

private readonly structure = viewChild('structur')

constructor() {
  effect(() => {
    // This might be called twice if the navigation has completed
    // and if the structure has been resolved
    const navigationEnd = this.navitationEnd();
    const structure = this.structure();

    // Scroll into view logic can go here
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

updateOne is limited to updating a single field at a time and does not have the capability to generate new fields within

I have encountered an issue with my NodeJs and MongoDB atlas setup while trying to save/update user profiles. The updateOne method seems to only update a single field at a time instead of the entire record. Here is the relevant code snippet: app.post(" ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...

What significance does it hold for Mocha's `before()` if the function passed requires parameters or not?

In one part of my code, I have a describe block with before(a) inside. The function a originally looks like this: function a() { return chai.request(app) ... .then(res => { res.blah.should.blah; return Promise.resolve(); }); ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

Why is Jasmine throwing an error when I try to use getElementsByTagName(...)?

HTML: <ul id="listONE"> <li class="{{isSel}}" ng-repeat="person in people" ng-click="selPersonToChange(this)">{{person.name +" - "+ person.city}}</li> </ul> A snippet from my script.js using AngularJS (1.3.1): mymod.control ...

Designing a website similar to sevenly.org using jquery: A step-by-step guide

My understanding of javascript and jquery is at a beginner level. I am interested in creating a design similar to Sevenly, where one page/div moves over another. I'm not sure where to begin with this. Any advice or ideas on how to implement this effec ...

Transform ECMAScript Observable / Zen Observable into RXJS Observable

I currently have an ECMAScript Observable that is compliant with specifications, specifically sourced from the wonka library. I am facing challenges in converting this type of observable to an rxjs 6 observable. It appears that this conversion was possibl ...

The status code 0 was returned for the null URL

I am facing an issue with my Ionic 3 application that is using the same API as my previous versions of Ionic apps. After logging in, I encountered the following error: Response with status: 0 for URL: null I have researched online and found suggestion ...

Azure function indicates a successful status despite receiving a result code of 500

I have an Azure function containing some logic with a basic try-catch structure (code shortened). try { // perform logic here that may fail } catch (ex) { context.log(`Logging exception details: ${ex.message}`); context.res ...

Error message encountered: Failed to convert 'text' to a string using Selenium webdriver

As a beginner in selenium, I have recently set up my environment with the latest versions of selenium web driver 3.4, Node.JS v8.2.0, and the gecko driver. I have also configured my environment variables. Currently, I am writing my tests using Visual Stud ...

Scroll Magic not cooperating with Simple Tween local copy

Greetings! I am attempting to replicate this simple tween example using scrollmagic.js. It functions properly on jsfiddle. To confirm, I added scene.addIndicators() to observe the start, end, and trigger hook. It functions flawlessly. As displayed in the ...

Generate a D3.js vertical timeline covering the period from January 1, 2015 to December 31, 2015

I am in need of assistance with creating a vertical timeline using D3.js that spans from the beginning of January 2015 to the end of December 2015. My goal is to have two entries, represented by colored circles, at specific dates within the middle of the t ...

Navigational module and wildcard for routes not located

I have my routing configuration structured as follows: app-routing const routes: Routes = [ { path: 'login', loadChildren: 'app/modules/auth/auth.module#AuthModule' }, { path: '', redirectTo: 'dash ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

Upon encountering an expression, the code anticipated either an assignment or a function call, but instead found an expression, triggering the no

When using the forEach method within a function in JavaScript, I encountered a code compilation failure with the following error: Expected an assignment or function call and instead saw an expression no-unused-expressions. This error occurs for both ins ...

AngularJS ng-focus does not function properly with iframes

Why isn't ng-focus working with iframe in AngularJS? What am I missing? Take a look at my code: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <iframe src="example.com" tabindex="-1" ng-fo ...

Guy discussing the ins and outs of JavaScript variables

I am facing an issue with retrieving the value in the jQuery script. The value should be taken from route_path_images, but it's not showing up. var route_path_images="http://www.domain.com" jQuery("#header_background_night_star").fadeIn(2000).css("b ...

Angular Material Slider is failing to display properly

I am struggling to get the Angular Material Slider to render correctly in my project. Here is the code I have been using: <div class="row formField" ng-cloak> <div class="col-md-2"> <div>送貨日期</div> & ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...