Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }).

My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag

This is my target

<h1 #formUpdate class="titles">{{ editOrCreate$ | async }}</h1>

First Approach

Here is the HTML code that I need to make work

<mat-menu #menu="matMenu">
    <button mat-menu-item (click)="formUpdate.scrollIntoView({ behavior: 'smooth', block: 'start' })">Top</button>
</mat-menu>

The code above is not working, but if I try it in a different way, like a button outside my table, it works Code I have tried

<button mat-button (click)="formUpdate.scrollIntoView({ behavior: 'smooth', block: 'start' })">Top</button>

The code above works

Second Attempt

I attempted to do it in the file.ts, as shown in the code below

file.html

<mat-menu #menu="matMenu">
    <button mat-menu-item (click)="updateItem(formUpdate )">Top</button>
</mat-menu>

file.ts

export class WorkspacesComponent{

    public updateItem(formUpdate){
        target.scrollIntoView({ behavior: 'smooth' });
    }
}

All code.html

[... full HTML code here ...]

file.ts method

public updateItem(workspace: Workspace, updateOption: string = '', formUpdate) {
        let description;
        formUpdate.scrollIntoView({ behavior: 'smooth', block: 'start' })
        if (updateOption === 'Criar Versão Assunto') {
            description = `Criado a partir do workspace '${workspace.name}' em ${new Date().toLocaleDateString()}`;
            updateOption = 'Criar Assunto';
        } else {
            description = workspace.description;
        }
        this.store.dispatch(new userActions.WorkspacesSelect(workspace._id));
        this.language$.next('pt-br');
        this.workspaceForm$.next(this.newForm(workspace.name, description, workspace.language));
        this.store.dispatch(new userActions.WorkspaceEditOrCreateState(updateOption));
    }

Both cases are not working.

I require assistance in making it work similar to my attempt with a mat-button outside my table

Answer №1

What helped me was putting the scrollIntoView() function inside a setTimeout.

scrollToElement(el: HTMLElement) {
  setTimeout(()=> {
    el.scrollIntoView({behavior: 'smooth'});
  }, 0);
}

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

Guide on compiling SCSS to CSS when running npm start

When running my application with npm start, I'm unable to compile scss files to css live. Is there a way to achieve live reload for sass to css similar to how ts are compiled to js by the tsc:w utility? Currently, I have to stop the build, then run gu ...

Invoking a JavaScript class using a script tag

In my code, I have a class declaration in a script that is imported before the body tag: $(document).ready(function(){ var FamilyTree = function() { }; FamilyTree.prototype.displayMessage=function() { alert("test"); } }); Then, within the bo ...

Clear the cache in Angular to remove the page

Within my current project, I am utilizing angular's $routeProvider to dynamically load pages into an ng-view section. The loaded pages are displaying correctly in the ng-view and are being cached for quick access without needing to make a new server r ...

Generating ng2 chart data dynamically within Angular 4

In my latest project, I've developed an application that retrieves data from a service in JSON format and displays it on a UI chart. However, I've encountered a recurring issue where the data does not bind properly to the chart despite multiple ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

Having difficulty sending a message from an AngularJS application to an Angular 10 application through an iframe

I have two applications running locally - one is an AngularJS application and the other is an Angular 10 application. I am trying to access a page from the Angular 10 application using an iframe and send a message to it from the AngularJS application. How ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" Attempting to achieve this ...

Learn the process of dynamically wrapping component content with HTML tags in Vue.js

Hey there! I'm looking to enclose the content of a component with a specific HTML tag, let's say button for this scenario. I have a function that dynamically returns a value which I use as a prop. Based on that, I want to wrap the component&apos ...

What is the proper way to update data in reactjs?

I previously had code that successfully updated interval data in the browser and locale without any issues. class Main extends Component { constructor(props) { super(props); this.state = {data: []} } componentWillMount() { fetch('fi ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

Received undefined instead of a Promise or value from the function in Nodemailer

I'm currently exploring cloud functions and trying to implement email notifications for document creation triggers in Firestore. I found a helpful tutorial that guided me through the process, but I encountered an error while analyzing the cloud functi ...

Transferring arrays through curl command to interact with MongoDB

Here is my mongoDB schema used for storing data: const mongoose = require("mongoose"); const subSchema = require("../../src/models/Course"); const All_CoursesSchema = new mongoose.Schema({ Student_name: { type: String, required: true ...

Prevent all click and keyup events from being activated until the ajax call finishes

Is there a way to prevent all links from being activated until an ajax call is complete? I am looking for a solution that works for both click events and keyup triggers. In essence, what I am after is: - The Ajax link is activated (either through a clic ...

The imported js elements from Bootstrap are failing to function properly despite being successfully included

I want to utilize the collapse feature from Bootstrap in my project. To do so, I have installed jQuery and popper.js: "styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/hover.css/css/hover.css", "node_modules/hambur ...

Execute JavaScript unit tests directly within the Visual Studio environment

In search of a method to run JavaScript unit tests within the Visual Studio IDE, I currently utilize TestDriven.net for my C# units tests. It's convenient to quickly view the test results in the output pane and I am seeking a similar experience for Ja ...

I am facing an issue where the URL generated in the Controller in Laravel is not functioning properly when

After escaping the single quote, I included a URL link inside the Controller and passed it through json_encode. However, when I clicked on the URL link, it did not work and showed this: The URL appeared like this: http://localhost/BSProject/public/%7B% ...

Switch the 360-degree images by clicking a button using Panolen.js

As a beginner in the world of html, css, and javascript, I am trying to create a webpage that displays 360 panorama images. My goal is to have the image change when a button is clicked - for example, clicking on button 1 will display image1, while clicking ...

Automate CSS slideshow playback using JavaScript

Using only CSS, I created a basic slideshow where the margin of the element changes upon radio button click to display the desired slide. You can view the functionality in the code snippet below. Additionally, I implemented auto play for this slideshow usi ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...