I keep encountering an issue with a TypeError that says I am unable to read properties of undefined, specifically 'nativeElement'. Can anyone provide guidance on resolving this error

Here is the current state of my code:

<mat-tree-node>
...
 <div *ngIf="node.type=='assembly' || node.type=='part'" style="display: inline;"
                    (contextmenu)="asmStateServ.contextMenu($event, node.name)">{{node.instanceName}}
                    ({{node.name}})
                    <div class="customContext" (click)="asmStateServ.stopPropagation($event)" #menu>
                        <ul>
                            <li (click)="asmStateServ.selectNode(node.name)">Select</li>
                            <li (click)="asmStateServ.deSelectNode(node.name)">Deselect</li>
                        </ul>
                    </div>
                </div>
</mat-tree-node>

This is how it looks in the .ts file:

@ViewChild('menu') menu: ElementRef
    public contextMenu(event: MouseEvent, node: asmTreeNode | asmTreeNodeFlat | asmTreeNodeScene) {
        event.preventDefault();
        this.menu.nativeElement.style.display = "block";
        this.menu.nativeElement.style.top = event.pageY + "px"
        this.menu.nativeElement.style.left = event.pageX + "px"

    }

    public disappearContextMenu() {
        this.menu.nativeElement.style.display = "none";

    }

    public stopPropagation(event: any) {
        event.stopPropagation();

    }

However, the issue persists where the menu fails to open and a specific console error remains. Can you help me identify what may be causing this problem? I am fairly new to Angular and programming as a whole, so correct guidance would be greatly appreciated :)

Answer №1

It seems like you are trying to utilize @ViewChild in the property asmStateServ, which appears to be a service that is injected. The use of @ViewChild('menu') is only valid within the property initializers of the component class, not in an injected service. However, you can still pass the element as a parameter to these methods. It's important to note that this passes an HTMLDivElement, not an ElementRef.

Here are the relevant details:

<mat-tree-node>
  ...
  <div (contextmenu)="asmStateServ.contextMenu($event, menu)">
    ...
    <div #menu>...</div>
  </div>
</mat-tree-node>
    public contextMenu(event: MouseEvent, menu: HTMLDivElement) {
        event.preventDefault();
        menu.style.display = "block";
        menu.style.top = event.pageY + "px";
        menu.style.left = event.pageX + "px";
    }

Answer №2

Prior to accessing the nativeElement, consider adding a null check.

        Verify if this.menu?.nativeElement?.style.display = "none"; returns null before proceeding.

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

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

Is there a way to keep track of changes in multiple dropdowns without having to create a separate JavaScript function for each one

I'm looking for a way to dynamically add more dropdowns as my website grows without having to keep adding new functions to the JavaScript code. Is there a solution for this? Currently, I can add additional functions to the JavaScript like this: ...

Purge the localStorage every time the page is refreshed in Angular 2

After successful authentication, I am storing a token in localStorage. However, every time I refresh the page, I need to delete the token and redirect to a specific router. I'm struggling to find a way to achieve this in Angular, so currently I' ...

Expanding angularjs date filter to support additional date formats

When working with Angularjs, you can utilize the Date Filter to format dates. Is there a way to get the date in the format outlined below? dd(st || nd || th) mm yyyy 1st May 2014 1<sup>st</sup> May 2014 Should I develop a new custom filter fo ...

What is the best way to render components with unique keys?

I am currently working on a dashboard and would like to incorporate the functionalities of React-Grid-Layout from this link. However, I am facing an issue where the components are only rendered if they have been favorited. In order to utilize the grid layo ...

Encountering a [object Object] error at the AppComponent_Host ngfactory js file while working on an Angular 8

While attempting to run the official sample angular app provided by Microsoft Identity platform (which utilizes the MSAL library for authenticating Azure AD users), an error is encountered. It seems that there may be a challenge in pinpointing the specific ...

Exploring the world with Algolia's search capabilities

I've been working on implementing geo search with Algolia for a web project. Here's the code snippet I have so far: var searchClient = algoliasearch(Algol_APP_ID, Algol_API_KEY); var itemIndex = searchClient.initIndex('item'); functio ...

Ways to utilize the useRef method within the useContext hook while implementing Typescript

Struggling to incorporate useRef into my global Next.js useContext function while utilizing TypeScript. Attempted approach and encountered errors: interface tripAttributes{ tripTitle: string } const initialTripState: tripAttributes = { tripTitle ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

Converting a 'div' element into a dropdown menu with CSS and Jquery

I am facing a challenge where I have a collection of buttons enclosed in a div that I want to resemble a dropdown: <div id = "group"> <label> Group: </ label> <div value =" 1hour "> 1h < / div> <div value =" 2hou ...

Having issues with images not loading and receiving a 401 error with the API while using Vite in a production build

While working on my React project with Vite, I've encountered a few challenges during the production build process. Everything seems to be running smoothly when I use npm run dev, but when I try to build the project using npm run build and then previ ...

Execute a PHP SQL query when a link is clicked

To trigger a SQL query when a link is clicked, I have implemented the following code: mainpage.php: function deleteImage1() { $.post("delete_image.php", { num:1, id:<?php echo $id; ?> }, function(data,status){ alert("Data: " + data + "\n ...

Handlebars template engine does not support query parameters

Below is the code snippet I am working with: app.get("/editar-equipo?:id", (req, res) => { const equipos = obtenerEquipos() let equipoSeleccionado for(let i = 0; i < equipos.length; i++){ if(equipos[i].numeroId === ...

Exploring the relationships between schemas in Node.js using Mongoose and MongoDB

Hello, I am a beginner in utilizing MongoDB and Node.js and I have a query. Below is my product schema: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const categorySchema = require('./category'); const Produc ...

How can JavaScript be used to deactivate an HTML form element?

Within this form, there are two selection buttons that require client-side validation. The user must choose one of them, and once a selection is made, the other button should automatically be disabled. Below is the script I have implemented: <html> ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

Utilize Typescript/Javascript to utilize the Gmail API for sending emails via email

I am trying to send emails from my application using my Gmail account with Ionic. I have followed tutorials from SitePoint and Google Developers. Here is how I'm initializing the client: client_id: gapiKeys.client_id, discoveryDocs: ["https://www.goo ...

Discover the underlying element that is being blurred when clicked

Is there a method to determine which element triggered the blur event when clicked outside? I want to update a ui-select value to match what the user typed in if they click outside of the dropdown. However, if they click on a dropdown item, I want to disc ...

Leave a message | Google Sheets | JavaScript using nodeJS

I am having trouble adding comments to cells using the "Google Spread-Sheet" module in NODEJS. I have successfully written to cells, read from them, and deleted them, but I can't figure out how to add a comment to a cell. The tutorials I have found on ...