Display or conceal <ul> with a click using AngularJS

I am struggling to display a menu on my HTML page. Currently, it is showing all the submenu options instead of just the options related to the clicked item.

Here is the code from my home.html file:

  <ul class="navbar-nav">
    <li data-toggle="dropdown" class="nav-item" *ngFor="let page of list;let i = index" id="id{{page.link_id}}"><span  (click)="showsubmenu(i)">{{page.link_name}}<i class="iconn" *ngIf="page.flg[0].SHOW_ICON=='YES'"><ion-icon name="md-arrow-dropdown"></ion-icon></i></span>

     <ul *ngFor="let sublink of page.sublink; let j=index;"><li >{{sublink.SUBLINK_NAME}}</li></ul>


    </li>
  </ul>

The default behavior is displaying all submenu options, as shown in the screenshot below:

https://i.sstatic.net/81Wcd.png

Here is the home.ts code for reference:

export class HomePage {

 list = [];submenu;
  json_data = [
    {"link_id":"38","link_name":"Contact","flg":[{"SHOW_ICON":"NO"}],"sublink":[]},
    {"link_id":"37","link_name":"Offices","flg":[{"SHOW_ICON":"YES"}],"sublink":[{"SUBLINK_NAME":"test11","SUBLINK_OF":"37","SUBLINK_ID":"10005"}]},
    {"link_id":"34","link_name":"Products","flg":[{"SHOW_ICON":"YES"}],"sublink":[{"SUBLINK_NAME":"Quick Patrol","SUBLINK_OF":"34","SUBLINK_ID":"10004"},{"SUBLINK_NAME":"Link2","SUBLINK_OF":"34","SUBLINK_ID":"10013"}]},
    {"link_id":"33","link_name":"Home","flg":[{"SHOW_ICON":"NO"}],"sublink":[]}
  ];

  constructor(public navCtrl: NavController) {
this.list = this.json_data;
  }


  showsubmenu(index){

    this.submenu= this.list[index]["link_id"];
    console.log(this.submenu);
    this.submenu=this.list[index]["sublink"];
    console.log(this.submenu.length);

  }
}

Answer №1

Add a new feature to store the index of the open menu in order to toggle the submenu using ngIf:

HTML:

//Click event for first li
<li (click)="show === i ? show =- 1: show = i" ....>

//Display second li based on show value
<li *ngIf="show === i">....

Typescript:

...
show = -1;
...

DEMO

Answer №2

<ng-container *ngIf="page.flg[0]=='NO'?null:true"><ul *ngFor="let sublink of page.sublink; let j=index;"><li >{{sublink.SUBLINK_NAME}}</li></ul></ng-container>

When working in the *.ts file, consider adding:

showsubmenu(index) {
  this.list[index]['flg'][0] === 'NO'? 'YES' : 'NO';
}

It is recommended to keep the 'flg' key as a boolean instead of an array of strings. Instead of using 'showsubmenu()', you can handle the value of the 'flg' key directly in the HTML like:

(click)="page.flg?null:true"

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

How can one break down enum values in typescript?

I've defined an enum in TypeScript as shown below: export enum XMPPElementName { state = "state", presence = "presence", iq = "iq", unreadCount = "uc", otherUserUnreadCount = "ouc", sequenc ...

Implementing Multiple Exports within the next.config.json File

I am trying to combine withPWA and withTypescript in my configurations but I'm not sure how to do it... This is the code in my next.config.json file : const withPWA = require("next-pwa"); module.exports = withPWA({ pwa: { dest: "public", }, ...

What is the best way to combine API calls using rxJs subscribe and map in Angular?

Currently, I am executing multiple API requests. The first one is responsible for creating a User, while the second handles Team creation. Upon creating a User, an essential piece of information called UserId is returned, which is crucial for the Team cre ...

Steps for adding a sound effect, such as a button click noise, when clicking on a div tag

I'm currently working on an app using the Ionic Framework and I need a quick and easy method to play a sound when a div is clicked. Here's what I have so far: <div ng-click="sound()"></div> $scope.sound = function () { //play so ...

The function is not properly defined for the provided service

I am facing an issue with a service that is provided in app.module.ts and injected into an exported function within the same module. Despite this setup, when running the code inside MSALInstanceFactory, it is indicating that the service is undefined. impor ...

Error in Angular caused by ChartJS: TypeError, inability to access property '_model' because it is null

I am currently working on a project that involves showcasing real-time data in a ChartJS graph. The data is retrieved from an external web server, and I have managed to store the data in 6 arrays (which are constantly changing) with each array containing 1 ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

issues arise when deploying the Angular application on GitHub pages

Encountered an error while attempting to deploy my Angular application on GitHub pages using angular-cli-ghpages https://i.sstatic.net/ATIbR.png The bash commands I used when pushing the website to GitHub were as follows: ng build --prod --base-href ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

Transmit data to a modal popup in Angular 8

Here is the code snippet written in .ts file: openFormModal(id: number) { console.log(id); const modalRef = this.modalService.open(PartidoComponent); modalRef.componentInstance.id = id; //modalRef.componentInstance.id = id; modalRef.r ...

Angular Regular Expression Directive

I am attempting to develop an Angular Directive in Angular 7 that allows users to input a RegExp through an input property and restricts them from typing characters that do not match the specified RegExp pattern. While it is partially functional, I am enc ...

How to use Angular i18 for localizing the value of an interpolated string in a

In my Angular application, I have two translations in xliff format. The first one is @@field-is-required, which includes a string interpolation, and the second one is @@lastname, a regular translation. <trans-unit id="field-is-required" dataty ...

angular-oauth2-oidc - Issue with missing 'State' and 'Scope' parameters

One crucial requirement set by the identity server is to refrain from including 'state' and 'scope' in the URL. The specified request format is as follows URL?app=xxx&response_type=code&client_id=yyy&state=zzz&redirect_ ...

Multiple invocations of the callback function in an Angular5 template binding

In trying to create a grid component that uses structured data containing definitions for columns and an array of data. Each column definition includes a callback function to customize the display of that specific column's value. Within each callbac ...

TypeScript introduces a flexible generic type, Optional<T, Props>, allowing customized props for a specific

In my attempt to develop a type called Optional<T, TProps>, where T represents the initial type and TProps is a union type of properties that need to be optional. As an illustration: type A = Optional<{a: string, b: string}, 'a'&g ...

Issue encountered with UglifyJs - Unexpected token: title (Subject)

My attempt to deploy my initial Angular application is not going smoothly. The build process fails and the error message I'm encountering states: ERROR in vendor.809dd4effe018f6b3d20.bundle.js from UglifyJs Unexpected token: name (Subject) [vendo ...

Angular 2 Template - Show alternate content if the string is empty

Back in the AngularJS days, there was a neat trick where you could bind data to a string directly in the markup like this: {{myString | 'N/A'}} This little trick would check if the string was empty and if so, display 'N/A' instead. It ...

Evaluating the initial value from an array for radio buttons in Angular using Typescript

I am trying to retrieve the first value from an array that I receive through a get request via an api. Below is my HTML code: <div class="row" class="select-options" *ngFor="let options of paymentOptions;let idx = index"&g ...

Angular6 ng test is not successful

I recently upgraded my project from Angular4 to version 6. Everything seems to be working fine, except for the issue with running ng test: ERROR [karma-server]: Server start failed on port 9876: Error: No provider for "framework:@angular/cli"! (Resolving ...

Instead of the type definition file, navigate to the TypeScript source file within VS Code

A unique npm library I developed is utilized in various main projects, with all the sources stored within a /src directory and written in TypeScript. The compiler options listed in the tsconfig.json file include "sourceMap": true and "outDir": "dist". Addi ...