Is there a way to navigate to a specific component selector within an ngFor loop?

I have a scenario where I have multiple components running inside *ngFor on the same page. My goal is to create button links at the top of the page that, when clicked, will scroll to the corresponding component on the page.

Below are the code snippets that I am currently working with:

In the HTML file:

<button (click)="scroll(target)"></button>
<div #target>Your target</div>

And in the TypeScript file:

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

However, I am unsure of how to reference each individual component's selector.

Here is a snippet of my code without implementing the above functionality yet:

// There will be many buttons to link to each of the components.

<button type="button" (click)="scroll()">Click this button to navigate</button>

<div *ngFor="let appdata of appData">
    <app-details [value]="appdata"></app-details>
</div>

The 'appdata' variable is a JSON object containing attributes like appID (which could be used to uniquely identify each component), title, description, etc.

Please provide guidance on how I can reference the components and possibly suggest an implementation strategy. Thank you!

Answer №1

You have the ability to create something along these lines.

<div *ngFor="let appdata of appData; let i = index;">
    <app-details [id]="i" [value]="appdata"></app-details>
</div>

Upon clicking the scroll button, you can implement TS code to focus on a specific area:

const element = document.querySelector(id); // id reference of the scroll target element
element.scrollIntoView();

Answer №2

If you want to scroll to a specific element on a webpage, JavaScript provides the window.scrollTo(xpos, ypos) function.

Here's how you can achieve this:

Firstly, create a variable that represents the window object.

win:Window = window;

Next, implement the scroll functionality:

scroll(component) {
    this.win.scrollTo(0, component.offsetTop);
}

The parameter 'component' should indicate the specific element you want to scroll to, and component.offsetTop gives you the vertical position of that element.

In your HTML code:

<span *ngFor="let target of win.document.getElementsByTagName('app-details'); let i=index" >
    <button (click)="scroll(target)">Go To {{i}}</button></span>

Answer №3

In order to achieve my goal, I needed the list to scroll into view once it was constructed. This solution is based on @Abhishek's response and this particular answer.

<div *ngFor="let appdata of appData; let i = index;let isLast = last">
    <app-details [id]="'item' + i" [value]="appdata"></app-details>
    <span *ngIf="isLast">{{ scrollIntoView('item' + i) }} </span>
</div>

To implement this in your typescript file:

  scrollIntoView(id: string) {
    const element = document.getElementById(id);
    element?.scrollIntoView();
  }

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

Enhancing React Flow to provide updated selection and hover functionality

After diving into react flow, I found it to be quite user-friendly. However, I've hit a roadblock while attempting to update the styles of a selected node. My current workaround involves using useState to modify the style object for a specific Id. Is ...

Trouble merging latest values using RxJS combineLatest in Angular 12

Having difficulties with combining multiple filter values in API call. I have 3 filter values and want to make a combined call when there is a selection change, but only one value is showing up in 'combineLatest'. Please guide me on where the iss ...

Using `ngIf` with a condition causes the original object to be lost in the `let` binding

Imagine I am keeping track of the user currently logged in using this approach. If the user is null, it means they are not logged in. When logged in, they can either be anonymous (without a name) or have a name. interface User { name?: string; } current ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Enhance your Fastify routes by incorporating Swagger documentation along with specific tags and descriptions

Currently, I am utilizing fastify 3.28.0 in conjunction with the fastify-swagger plugin and typescript 4.6.2. My goal is to include tags, descriptions, and summaries for each route. As per the documentation found here, it should be possible to add descrip ...

Show the CustomError message and HTTP status code that was raised by the server in the HttpErrorResponse

I am in the process of developing an ASP.NET Core API server paired with an Angular client. One of my main objectives is to ensure that the client can effectively capture any exceptions thrown by the server. I have implemented an HTTP Interceptor in Angula ...

Is it possible to modify the dropdown menu so that it opens on the right side instead of using a select tag?

Is there a way to make the drop-down from the select tag open to the right side(drop-right)? <label for="ExpLabel">Select Message Expiry:</label> <select name="ExpSelect" id="Expiry"> <option value="ExpiryDate">1 Day</opt ...

Angular2 encountering a lack of service provider issue

After finding the code snippet from a question on Stack Overflow titled Angular2 access global service without including it in every constructor, I have made some modifications to it: @Injectable() export class ApiService { constructor(public http: Http ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

It seems like the recent upgrade to yarn 2 has caused issues with typescript types, whereas the installation of the same project with yarn 1 was

Recently, I've been attempting to update a typescript monorepo to utilize yarn 2, but I've encountered an issue where typescript is struggling to recognize certain react props. This functionality was working fine in yarn 1.x, leading me to believ ...

What is the process for defining a type that retrieves all functions from a TypeScript class?

Imagine having a class called Foo class Foo { bar(){ // do something } baz() { // do something } } How can you define a type ExtractMethods that takes a class and returns an interface or type containing the class methods? For example: t ...

Angular 9 ensures that the component template is validated and loaded before the constructor logic is executed

Recently switched from Angular 8 to Angular 9 (without IVY) and encountered some unusual errors indicating that services injected in components are undefined in getters. Upon investigation, I discovered that the getter is being called before the constructo ...

Create multiple instances of a component in a dropdown menu using different datasets in Angular 5

Outlined below is the structure of my drop-down list: Companies > Depots Each company has multiple depots. I have developed a component for companies, and upon clicking on a company (menu item), an HTTP request is made to bring all companies which are th ...

Is it more beneficial to convert all the current jQuery AJAX webparts into Typescript or should I opt to inject the existing jQuery into SPFX instead?

Transitioning from SharePoint 2013 to SharePoint online raises the question of how to migrate existing webparts that utilize jquery - ajax to SPFX client webparts. One possibility is rewriting all the code in Typescript, but is it possible to simply inje ...

Tips for efficiently utilizing Hooks with React Context:

I am currently working on my application and utilizing React Context with the setState function. const userContext = React.createContext([{ user: {} }, () => {}]); const userHook = useState({ user: {} }); <userContext.Provider value={userHook}> / ...

What is the best way to compare two TypeScript object arrays for equality, especially when some objects may have multiple ways to be considered equivalent

Currently, I am in the process of developing a cost function for a game where players are given a set of resources in their hand. The resources can be categorized into different types such as Fire, Air, Water, Earth, Good, Evil, Law, Chaos, and Void. Thes ...

Error message in Angular Reactive Forms: Control with specified path cannot be found

My current challenge lies within the component: cabinet-clinic-form.component.ts. I am facing an issue with FormGroup validation in my clinics FormArray. Upon rendering the page, I encounter an error as shown in this screenshot. Despite attempting to dynam ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

execute the angular service within the "then(function(){})" block

I have a specific requirement where I need to capture a screenshot of a view when the user clicks on a button, send it back to the backend to save as a PDF in the database, and then allow the user to download the same image. Currently, I am utilizing the D ...

Triggering two function calls upon submission and then waiting for the useEffect hook to execute

Currently, I am facing a challenge with form validation that needs to be triggered on submit. The issue arises as some of the validation logic is located in a separate child component and is triggered through a useEffect dependency from the parent componen ...