Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving this issue?

Here is what I have done so far, but it displays the entire list instead of just the element that was clicked:

    document.getElementById("menu-content").addEventListener("click",function(e) {
      const input = event.target as HTMLElement;
      console.log(input.nodeName);
      if(e.target && input.nodeName == "LI") {
        (document.getElementById('txt') as HTMLElement).innerHTML = input.innerText;
      }
    });
    <ul id="menu-content" class="menu-content collapse out">

      <li id="node1" ><i class="fa fa-dashboard fa-lg"></i> Dashboard </li>
      <li id="node2" data-toggle="collapse" data-target="#statistics" class="collapsed">
        <i class="fa fa-area-chart fa-lg"></i> Statistics <span class="arrow"></span>
      </li>

      <ul class="sub-menu collapse" id="statistics">
        <li id="node21">Tests</li>
        <li id="node23">Devices</li>
        <li id="node24">Builds</li>
        <li id="node25">Services</li>
        <li id="node26">Projects</li>
      </ul>

      <li id="node3" data-toggle="collapse" data-target="#reports" class="collapsed">
        <i class="fa fa-file-text fa-lg"></i> Reports <span class="arrow"></span>
      </li>

      <ul class="sub-menu collapse" id="reports">
        <li>Tests</li>
        <li>Devices</li>
        <li>Builds</li>
        <li>Services</li>
        <li>Projects</li>
      </ul>

      <li id="node4"><i class="fa fa-wrench fa-lg"></i> Configurations </li>

      <li id="node5" data-toggle="collapse" data-target="#overview" class="collapsed">
        <i class="fa fa-book fa-lg"></i> Overview <span class="arrow"></span>
      </li>

      <ul class="sub-menu collapse" id="overview">
        <li>Tests</li>
        <li>Devices</li>
        <li>Builds</li>
        <li>Services</li>
        <li>Projects</li>
      </ul>

    </ul>

Answer №1

Take a look at this solution I crafted based on your query, but feel free to customize it for more versatility.

https://stackblitz.com/edit/angular-vpfat5

html

  <ul class="sub-menu collapse" id="statistics">
    <li *ngFor="let item of listItems;let i = index" (click)="onItemClick('statistics',i)">{{ item }}</li>
  </ul>

component

 listItems = ['Tests','Devices','Builds','Services','Projects'];
  onItemClick(category:string, index: number)
  {
    console.log(`${category} -> ${this.listItems[index]}`)
  }

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

Stop useEffect from triggering during the first render

I'm working on implementing a debounce functionality for a custom input, but I'm facing an issue where the useEffect hook is triggered during the initial render. import { useDebouncedCallback } from "use-debounce"; interface myInputProps { ge ...

Is it possible to target a specific element using Angular2's HostListener feature? Can we target elements based on their class name?"

Is there a way in Angular2 to target a specific element within the HostListener decorator? @HostListener('dragstart', ['$event']) onDragStart(ev:Event) { console.log(ev); } @HostListener('document: dragstart' ...

Create a single datetime object in Ionic (Angular) by merging the date and time into a combined string format

I have a string in an ionic project that contains both a date and time, and I need to merge them into a single datetime object for sending it to the server const date = "Fri Jan 07 2022 13:15:40 GMT+0530 (India Standard Time)"; const time = " ...

Searching for an Angular 7 alternative to Vue.js's "nextTick" function

In my Angular 7 project, I'm facing a situation where I need to automatically scroll to a specific section on the page after it has been fully rendered. The section is initially hidden using ngif and should only be scrolled to once it is visible in th ...

Is there a way to access a specific argument in yargs using typescript?

The idea behind using yargs is quite appealing. const argv = yargs.options({ env: { alias: 'e', choices: ['dev', 'prod'] as const, demandOption: true, description: 'app environment&apos ...

Unable to locate the module '@vitejs/plugin-react' or its associated type

After creating the project with npm create vite@latest and selecting ts-react, everything seemed to work fine when I ran npm run dev. However, in my vs code editor, I encountered the error message "Cannot find module '@vitejs/plugin-react' or its ...

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...

Send information to Angular's Google chart module

Currently, I am working with Google Charts in Angular 7 and have a specific requirement to dynamically pass the reportData into the drawChart function. var reportData = {"High":100, "Medium" : 200, "Low" : 300} generateChart() { setTimeo ...

Is it possible to utilize the HttpXsrfInterceptor and HttpXsrfCookieExtractor classes for CSRF configuration in Angular 16, despite Intelli-J indicating that they do not exist?

In a valuable article about configuring CSRF for Angular, two options are outlined: First: opt for the default Csrf configuration: providers: [ { provide: HTTP_INTERCEPTORS, useExisting: **HttpXsrfInterceptor**, multi: true } ] Second: If you're usi ...

Arranging Angular Array-like Objects

I am in possession of an item: { "200737212": { "style": { "make": { "id": 200001510, "name": "Jeep", "niceName": "jeep" }, "model": { "id": "Jeep_Cherokee", "name": "Cherokee", "nice ...

Having difficulty deploying the ASP.Net application in Visual Studio

While attempting to publish my app from Visual Studio, I encountered the following error: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 1. First Azure app C:...\firstazureapp C:...firstazureapp\firstaz ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

Troubleshooting Angular2: SVG Disappearing Upon Page Reload with PathLocationStrategy

I encountered a strange problem with SVG while using Angular2's PathLocationStrategy. The SVG code in my HTML template looks like this: <svg class="bell__icon" viewBox="0 0 32 32"> <use xlink:href="#icon-notificationsmall"></use&g ...

"Encountering a 404 Error when attempting to refresh an Angular 13 application hosted on an Apache

I have developed a prototype web application and now need to deploy it on an Apache server running Ubuntu OS. After building the web app, I hosted it on my local machine for testing purposes. I have configured the .htaccess file as follows: RewriteEngine ...

Following a successful compilation, the Angular application displays an empty page

Alert: Uncaught TypeError: Cannot read property 'length' of undefined at Object./src/components/Carousel.vue (Carousel.vue:123) at __webpack_require__ (bootstrap:1024) at Module../src/main.js (main.js:1) at __webpack_require__ (b ...

What is the best way to verify observables during the ngOnInit phase of the component lifecycle?

Despite reading numerous articles on testing observables, such as learning how to write marble tests, I am still struggling to find a clear solution for testing a simple observable in the ngOnInit lifecycle of my component. ngOnInit(): void { this.sele ...

Setting up the Angular 2 router to function from the /src subfolder

My goal is to create two separate subfolders within my project: src and dist. Here are the key elements of my application: root folder: C:\Server\htdocs\ app folder: C:\Server\htdocs\src index.html contains <base href="/ ...

Is it possible to create a prototype function within an interface that can group items in an array by a specific property, resulting in an array of objects containing a key and corresponding array of values?

I've been working on this code snippet and I'm trying to figure out how to make it work: Array<T>.groupBy<KeyType> (property): {key: KeyType, array: Array<T> }[]; The code looks like this: type ArrayByParameter<T, KeyType = ...

Guide on invoking a private function in Angular2 using RxJS Observables

Greetings, I am a beginner to RxJs and just started learning it today. As a newbie, I have a question regarding its usage. My current task involves extracting XML RSS feed and then converting it into a JSON format. To achieve this, I created a FeedService ...

TypeScript encounters difficulty locating the div element

Recently attempted an Angular demo and encountered an error related to [ts] not being able to locate a div element. import { Component } from "@angular/core"; import { FormControl } from "@angular/forms"; @Component({ selector: "main", template: ' ...