Navigating to a precise location on initial page load using Angular 11

Within the structure of my app, I have a parent component that displays a large image from a child component. When the parent component loads, I want the browser window to automatically scroll to a specific position in order to center the image.

Currently, there are inconsistencies in how the window scrolls: 1) on the initial load of the parent page, there is no scrolling, 2) when refreshing the page, the window does not scroll, and 3) navigating back to the parent component after being on the home screen causes the desired scrolling behavior.

How can I ensure that the window consistently scrolls to the correct position upon first loading the page?

Thank you all in advance!

Code samples

parent.component.ts

import { AfterViewChecked, Component } from "@angular/core";

@Component({
  selector: "app-parent",
  templateUrl: "./parent.component.html",
  styleUrls: ["./parent.component.css"]
})
export class ParentComponent implements AfterViewChecked {
  ngAfterViewChecked() {
    window.scrollTo(1900, 840);
  }
}

parent.component.html

<app-child></app-child>

child.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-child",
  templateUrl: "./child.component.html",
  styleUrls: ["./child.component.css"]
})
export class ChildComponent {}

child.component.html

<!-- link points to a non-specific 3840 x 2606 jpg image -->
<img src="https://i.imgur.com/5FpYloV.jpg" />

EDIT

I decided to use a free dragging directive on my main HTML element instead of scrolling around it. I find the dragging more user-friendly than waiting for the scrolling to complete.

Answer №1

Why not try scrolling within the child element?

export class ChildComponent implements AfterViewInit {
  ngAfterViewInit() {
    window.scrollTo(1900, 840);
  }
}

It's important to calculate the position correctly because the current code may not work properly on various devices.

You could implement something like the following:

<img #imageRef src="https://i.imgur.com/5FpYloV.jpg" />

export class ChildComponent implements AfterViewInit {
  @ViewChild('imageRef') image: ElementRef<HTMLImageElement>;

  ngAfterViewInit() {
    const rect = this.image.nativeElement.getClientBoundingRect();
    window.scrollTo(rect.x, rect.y);
  }
}

If the image is not loading when you attempt to scroll, you can also consider this approach:

<img #imageRef src="https://i.imgur.com/5FpYloV.jpg" (load)="scrollTo(imageRef)" /> 

export class ChildComponent implements AfterViewInit {

  scrollTo(image: HTMLImageElement) {
    const rect = image.getClientBoundingRect();
    window.scrollTo(rect.x, rect.y);
  }
}

Answer №2

It seems like you might need to implement scrolling functionality within the ngOnInit() method. For more information, refer to this helpful answer:

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

Add the mat-ripple effect to the host element with Angular 5 attribute directive

Is there a way to automatically include the mat-ripple directive on the host element of a custom directive I've made? The goal is to have mat-ripple added seamlessly to any element that uses my custom directive. For instance, when I add <button my ...

What is the best way to determine the position of the currently chosen selection in relation to the top

Let's say we have a situation like this: <select id="my-select"> <option id="iun">Option 1</option> <option id="sdd">Option 2</option> <option id="ert" select="selected">Option 3</option> <option i ...

Protecting against overflow for text inside a container that changes when hovered over

There is text displayed on top of an image within a div container that functions as a link. <a href="https://link.com" style="color:white"> <div class="thumbnail"> <img src="image.jpg" clas ...

Navigating through an interface array using *ngFor in TypeScript

After successfully implementing an interface to retrieve data from a service class, I encountered an issue when attempting to iterate through the FilteredSubject interface array. Despite using console.log, I was unable to achieve the desired outcome. You ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

The background-image property fails to display on a table element

I’m having trouble displaying a background image in a table within my Django app. Here’s the code I’m using: <table style="background-image: url('/static/assets/img/myimage.png') ;background-position: 0 100% !important;background-repeat ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

HTTP request form

I'm currently working on a form that utilizes XMLHttpRequest, and I've encountered an issue: Upon form submission, if the response is 0 (string), the message displayed in the #output section is "Something went wrong..." (which is correct); Howe ...

The importance of blending classes versus isolating classes in CSS selectors

Could somebody please direct me to the CSS hierarchy rules concerning "concatenated classes" versus "separated classes"? Furthermore, what are the correct terms for "concatenated classes" versus "separated classes" (I suspect that is why the documentation ...

Arrange the footer content into multiple columns

Hello! I'm currently working on creating a footer for my website. I've written this code and everything seems to be functioning correctly, except for the fact that the second row is positioned under the first row and taking up half of the bottom ...

Angular - Binding not displaying the latest list elements

In my small application, I have two buttons that either add 1 or -1 to a list. The sum of the list is also displayed. However, I am facing an issue with the interpolation as only the default values of the list are being displayed instead of the newly adde ...

When using ContentEditable in Firefox, it generates double line breaks instead of a single one

Noticed an interesting issue with div contenteditable where Firefox is interpreting 1 newline as 2 newlines. Is this a bug or am I overlooking something? Test it out in the example below by typing: Hello World within the contenteditable. When accessi ...

XPath //*[text()] is not picking up the desired text

Using the XPath 1.0 expression //*[text()] does not capture the phrase "now revenue of kfc is" https://i.stack.imgur.com/GeFCY.png However, with the XPath 2.0 expression //text(), it can be selected. https://i.stack.imgur.com/uTSqW.png Unfortunately, S ...

How to dynamically insert elements into the HTML page using Angular

When my page first loads, it looks like this <body> <div class="col-md-12" id="dataPanes"> <div class="row dataPane"> Chunk of html elements </div> </div> <div class"col-md-12 text-right"> <input type="butt ...

When Safari injects elements that were previously hidden with display:none, they remain visible

Using the JS library MagnificPopup, I implement popups on my website triggered by a "read more" button. This library moves the html to display it in a different location and then injects it back when the popup is closed. While this functionality works seam ...

Tips for modifying the height of a bootstrap-vue table and enabling scrolling with a fixed header

I have a div containing a b-table that I need help adjusting the height for. I want to make the table scrollable with a fixed header. Can anyone assist me? Here is my code: Code inside the template: <div class="tbl-barangay"> <b-table stripe ...

How can I optimize webkit-mask-box-image with a high-resolution Retina image?

Hey there, wondering if it's possible to achieve high-quality Retina-level CSS masking with the -webkit-mask-box-image property. Specifically, I'm trying to round the corners of an element without using border-radius due to performance issues: . ...

Angular2/4: Server-generated Alerts and Notifications

I'm in the process of developing a fresh Angular 2/4 application. One of the requirements for the homepage is to display urgent or emergency messages fetched from the server. I've explored several libraries but haven't found a suitable solut ...

What is the best way to eliminate whitespaces and newlines when using "document.execCommand("copy")" function?

I'm currently working on a code that allows users to copy highlighted text without using the keyboard or right-clicking. I also need to remove any extra spaces or line breaks using regex after the text is selected. However, I am facing some issues wit ...

Auto increment package.json version in a monorepo configuration

I am working on an Angular 6 app configured as a monorepo, comprising of a project that needs to be published to NPM along with a demo app. To update the versions of both the application and the project, I would like to utilize the npm version command. Th ...