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

Modify the JSON format for the API POST request

I need assistance with making an API POST call in Angular 8. The JSON object structure that needs to be sent should follow this format: -{}JSON -{}data -[]exp +{} 0 +{} 1 However, the data I am sending is currently in this format: - ...

Troubleshooting the Angular CLI issue: Module 'ansi-colors' not found

Having issues with my angular project, despite installing the latest version of NodeJs and NPM. When I try to run my project using the ng command, I encounter the following error message: Error: Cannot find module 'ansi-colors' Require stack: - ...

Transforming Observable into a Promise

Is it considered a best practice to convert an observable object to a promise, given that observables can be used in most scenarios instead of promises? I recently started learning Angular and came across the following code snippet in a new project using ...

Using the locale identifier en-GB can lead to date formats being displayed incorrectly

I'm struggling with setting up the correct locales in my Angular application. As per the documentation, I've inserted the following code snippet into my angular.json file. "projects": { "appname": { ..., "i18n&q ...

Issue with ReactJS Typescript: Cannot assign type 'number' to type '0, 8, 16, 24, 32, 40, or undefined'

I am looking to implement a grid from material-ui in react using typescript. You can view the live demo here. I have made adjustments to the example to make it work with typescript. Here is how my demo.jsx file looks like: import { withStyles } from &apo ...

Error: Import statement not allowed outside a module when using Material UI

I am relatively new to material UI. In my React project, I am incorporating material UI components. I am trying to implement a customized radio button following the instructions in the Mui documentation: https://mui.com/material-ui/react-radio-button/#cust ...

Error encountered in jsonwebtoken payload

Working on a web application with nodejs and angular cli, I have implemented JWT for login authentication. However, during the processing, I encountered the following error: Error: Expected "payload" to be a plain object. at validate (D:\Mean ...

Error: Unable to access postal code property since it is null in Angular 6

My application requires the user's firstName, lastName, email, mobile, and password. The User Account Information page should display fields such as firstName, lastName, mobile, gender, email, street1, street2, province, suburb, and postalCode. Howeve ...

Tips for eliminating duplicate entries in ag grid using Angular

Is there a way to eliminate the recurring assetCode entries in ag grid? The PRN and PRN1 values seem to be repeating unnecessarily. Check out the code below: list.component.ts ngOnInit() { this.rowData.push( { 'code': 'Machi ...

Is there a way to determine the total number of angular components in my app using IntelliJ IDE?

Seeking a way to determine the total count of angular components using IntelliJ IDE. I attempted 'find in files' search tool with the terms "export class" but it retrieved more than just component files. Appreciate any help! =) Etienne. ...

The functionality to close a Mat dialog is not functioning properly on Angular 11 with Material 11

I am trying to close the dialog by calling the close function of MatDialogRef instance, but unfortunately it is not working as expected. Within my ShareModule, there are components like HeaderCompose and LoginComponent. The HeaderComponent utilizes the Lo ...

Jasmine: A guide to mocking rxjs webSocket

Here is my chat service implementation: import {webSocket, WebSocketSubject} from 'rxjs/webSocket'; import {delayWhen, retryWhen, take} from 'rxjs/operators; import {timer} from 'rxjs; ... export class ChatConnectionService { priva ...

Tips for extracting individual fields from a payload in Angular 8

How do I extract individual fields from the payload and bind them with HTML on a page? I am trying to retrieve the alphacode and countryname in Angular 8. This is my Component: this.table$ = this.productService.get(id) .map(actions => { c ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

Display JSON information in a tabular format

I am trying to populate a table with data from an API response, but I am facing issues printing the data. Specifically, I need to match the "IdLangage" value with the correct cell in the table and display the corresponding translation. The JSON data format ...

Encountering Syntax Errors during Angular 6 production build

I encountered an issue with my project. Everything was running smoothly, and even when I executed the command ng build --prod, it compiled successfully and generated the dist folder in my project directory. However, after copying this folder to the htdoc ...

What do you do when you encounter an error message that says "Unable to find property 'startsWith'

autoCompleteSearch(event) { this.autocompleteData.forEach((entry) => { if (this.filterType === '1') { this.filteredResults = entry['items'].filter(item => item['item'] ? item['item'].startsWith(eve ...

When utilizing Ionic components in Angular, you may encounter the error message "element not recognized."

I have recently developed an app using Ionic and Angular, but I am encountering a persistent error. Whether I place the HTML code in the default Ionic generated "pages" folder or in a custom page, the error persists. Ionic version 5.4.16 Angular version 1 ...

Elevating font-awesome from version 4.7 to 5.11.1 in an Angular 6 project

Currently in my angular 6 project, the parent module utilizes font-awesome 4.7 as shown in package.json; "font-awesome": "^4.7.0", and angular.json; "styles": ["projects/adminUI/src/styles.css", "./no ...

Is it possible in Typescript to determine whether an object or function was brought in through an "import * as myImport" declaration?

Currently, I am importing all exports from a file in the following way: import * as strings from "../src/string"; After that, I assign a function to a const based on a condition: const decode = (strings._decode) ? strings._decode : strings.decod ...