Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfiddle.net/2dwvLg9u/

<nav appMenu class="navmenu navmenu-default" role="navigation">
  <ul class="nav navmenu-nav">
    <li class="active"><a href="#">Link</a></li>
    <li #testElem><a href="#">LinkTest</a>
      <ul class="hidden" #testElem1>
        <li><a href="#">Link1</a></li>
        <li><a href="#">Link1</a></li>
        <li><a href="#">Link1</a></li>
      </ul>
    </li>
    <li class="active"><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li class="active"><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li class="active"><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>

  </ul>
</nav>

Here is the typescript code:

import { Directive, Renderer2, OnInit, ElementRef, HostListener, HostBinding, Input, ViewChild } from '@angular/core';

@Directive({
  selector: '[appMenu]'
})
export class MenuDirective implements OnInit{

  constructor(private renderer: Renderer2) { }

  ngOnInit(){

  }
  @ViewChild('testElem') elRef:ElementRef;
  @HostListener('click') click(eventData: Event) {

    this.renderer.setStyle(this.elRef.nativeElement, 'display', 'block');


  }
}

Answer №1

A creative solution is presented here without the need for a directive. It involves directly manipulating the component view using a flag property to toggle the display of sub-options, controlled by *ngIf. While this approach works well, there is a small drawback where clicking on a child node also closes the parent node. However, this behavior can be prevented by calling event.stopPropagation() on the child click event. See below for more details:

HTML

<li (click)="showChild=!showChild" #testElem>
    <a href="#">LinkTest</a>
    <ul *ngIf="showChild" class="hidden" #testElem1> 
        <li (click)="onChildClick($event)"> //repeat it all for all child nodes
            <a href="#">Link1</a>
        </li>
 ...

Typescript

  showChild;
  ...
  onChildClick(event){
    event.stopPropagation(); // this will prevent parent node closing on child node click
  }

Check out the demo link

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

CSS Testimonial Slider - Customer Feedback Display

I'm having some issues with the code below: <div id="box"> <div class="wrapper"> <div class="testimonial-container" id="testimonial-container"> <div id="testimon ...

The functions.php file is failing to execute the JavaScript files located in the js folder

I've been attempting to incorporate a JS accordion into my Wordpress blog, but I seem to be encountering issues with the accordion.js file not loading through the functions.php file. Interestingly enough, when I manually add the js code in the header ...

Alter the status of a checkbox programmatically

There are two checkboxes available: <input type="checkbox" id="id3"></input> <input type="checkbox" id="id4"></input> The desired functionality is that when clicking on id3, id4 should also be checked. Initially, this works as e ...

What are the benefits of sharing source files for TypeScript node modules?

Why do some TypeScript node modules, like those in the loopback-next/packages repository, include their source files along with the module? Is there a specific purpose for this practice or is it simply adding unnecessary bulk to the module's size? ...

Guide on setting up staticfile_buildpack header configuration for an Angular application

After creating a build with ng build --prod, the dist/AppName folder was generated. Inside this folder, I found my manifest.yml and Staticfile. When I tried to do a cf push within the dist/AppName directory, everything worked as expected. However, I want ...

What is the most efficient way to incorporate Google Analytics code into the header tag of index.html?

If I were to receive the complete Google Analytics code from BE, what would be the most effective method of incorporating it into the index.html file? Just looking for a simple setup of GA. ...

Can NODE_PATH be configured in Typescript?

Before, I worked on my React app with ES6 and used NODE_PATH='src' to import files starting from the src folder. However, since switching to Typescript, I've realized that NODE_PATH is not supported. After some investigation, I discovered th ...

What are the steps to configure an option date for Yesterday, Today, and Tomorrow?

I have been working on setting options for dates like yesterday, today, and tomorrow. I have implemented the following code which is functioning properly, but it is not displaying yesterday's date. I want today's date to be selected and also disp ...

How to iterate through properties declared in an Interface in Angular 12?

Before Angular 12, this functioned properly: export interface Content { categories: string[] concepts: Topic[] formulas: Topic[] guides: Topic[] } //this.content is of type Content ['formulas', 'concepts'].forEach(c =&g ...

Is it necessary to incorporate ASP.Net MVC alongside Angular?

We are in the midst of developing a brand new web-based product. From the beginning, we committed to utilizing Bootstrap 4, Angular 4 and ASP.Net MVC 5 for the technology stack. However, as our project progresses, we have discovered that other components ...

The NgbTooltip does not activate when hovering over a <td> cell

I'm currently facing an issue with implementing ngbTooltip on <table> elements. Initially, I had trouble with <th>, but that was resolved by using the container attribute after referring to this helpful post. The main challenge arises ...

The function cannot be applied to d[h] due to a TypeError

Having some trouble with my code here. I'm trying to set up routes to display a gif using CSS animation when the page is loading. The gif shows up initially, but then everything fades out and the gif remains on the page. Additionally, I'm getting ...

JavaScript Execution Sequence: Demystifying the Order of Operations

I am struggling to comprehend the order of execution in the following code snippet. It is a portion of a larger script, but it all begins with $( "#select-overlay" ). function findSelectedMap(mapID) { $.getJSON('maps.json', function (json) { ...

Troubleshooting a problem with AJAX returning the data

Currently, I have a javascript function that calls another javascript function called zConvertEmplidtoRowid. This second function utilizes an ajax call to execute a query and retrieve data stored in a variable named rowid. My challenge lies in figuring out ...

AssertionError [ERR_ASSERTION]: The value of undefined is not equal to 390 in the GitLab

I'm a bit confused about the AssertionError [ERR_ASSERTION]: undefined == 390 in Gitlab. What I need is: The sumSalaries(obj) function, which should take an object obj as a parameter where the field names correspond to the employee's name and t ...

Is tsconfig.json necessary for JS libraries without TypeScript to include a .d.ts file when shipping?

I am currently in the process of creating a .d.ts file for an established JavaScript library that does not utilize the TypeScript compiler or include any TypeScript code. Should I include a tsconfig.json file in the library to ensure proper interpretation ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

JavaScript will continue to run uninterrupted even after refreshing the webpage

Has anyone else encountered the issue of a javascript on a page continuing to run even after the page is refreshed? From what I understand, javascript is single-threaded and should stop running when the page is refreshed. Just to provide some background, ...

C# - Implementing JavaScript Object manipulation in .NET Core

As I was browsing, I noticed many similar questions from years ago. Let's kick off this discussion with a simple JavaScript example showcasing how easy it is to modify, read, and write properties in objects using this language. Take a look at the cod ...

Unable to locate the identifier 'BrowserWindow'

In the providers folder of electron.service.ts, I have the following code: import { Injectable } from '@angular/core'; // If you import a module but never use any of the imported values other than as TypeScript types, // the resulting javascrip ...