Having trouble with the functionality of Angular 2 filter and toggle features?

I recently developed a hamburger menu with a toggle function to display subcategories. Everything was working smoothly until I applied a filter. Once I search for a category using the filter, the toggle function stops working.

Here is a snippet of my HTML code:

<ul class="nav navbar-nav">
<div id="menuToggle" class="sidenav">
<ul id="menu">
  <li>
   <input class="form-control" type="search" [(ngModel)]="txtToSearch" placeholder="Search"/>
  </li>
  <li *ngFor="let category of (componentContents.dashboardMenu | dashboardFilter : txtToSearch); let i = index" >
   <p class="toggleMenu" (click)="toggleMenu(i,componentContents.dashboardMenu)">{{category.category}}
    </p>

    <div *ngIf="category.show">
      <ul id="{{(category.category).split(' ').join('-')}}" *ngIf="category.subCategory.length > 0">
        <li *ngFor="let subCat of category.subCategory">
          <a routerLink={{subCat.router}} routerLinkActive="active">             
          <span class="glyphicon glyphicon-bell" ></span>{{subCat.subcategory}} </a></li>
      </ul>
    </div>
    <hr />
  </li>
</ul>

In my component.ts file, this is the code I am using for the toggle function:

toggleMenu(index, catArry) {
if (catArry[this.prevClicked] && this.prevClicked !== index) {
  catArry[this.prevClicked].show = false;
}
catArry[index].show = !catArry[index].show;
this.prevClicked = index;
 }

Answer №1

When applying the filter, the index variable only pertains to the current result. This means that as the result changes, the index no longer corresponds to the actual position of the element in the array.

Instead of passing the index to the toggleMenu(category, catArray) function, consider passing the category itself and calculating the index within the toggleMenu function using catArray.indexOf(category)

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

Enhancing data entry by using a dropdown menu to update the record value without adding any undefined data elements

Currently, I am working on enhancing a Location edit form that includes an API-fed dropdown list of Departments. The task involves utilizing the record's departmentId to preselect the current value in the dropdown menu. However, a complication arises ...

How can I retrieve the HEX code of a color from an image when hovering or clicking?

Is there a way to retrieve the hexadecimal code of a pixel within an image displayed on a webpage using jQuery, without relying on the canvas element? I am specifically interested in obtaining the actual color code of the image itself, not the background c ...

Retrieve both the name and id as values in an angular select dropdown

<select (change)="select($event.target.value)" [ngModel]="gen" class="border border-gray-200 bg-white h-10 pl-6 pr-40 rounded-lg text-sm focus:outline-none appearance-none block cursor-pointer" id="gend ...

Using jQuery code within PHP pages is a convenient and powerful way to

I am currently facing an issue with PHP and jQuery. Here is the structure of my website: header.php - contains all css and js files. index.php - main page. sidemenu.php - includes the side menu in index.php Within sidemenu.php, I have the following JS ...

Encountered an issue when trying to install angular-cli globally using command prompt

Recently, I attempted to set up Angular CLI on my Windows operating system. As a novice in this area, I relied on the steps provided at to configure my development environment. Since I am using Windows, I opted for the "nodist" NVM method to install node ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

SharePoint Online / Angular - Issue: Unhandled Error: Zone is already loaded

I recently completed a project in Angular and integrated it into a SharePoint page using the Content Editor. Everything was running smoothly until yesterday, when I encountered an error while loading the page. zone-evergreen.js:42 Uncaught Error: Zone alre ...

Modify the color of the title in a bootstrap vue tab

Utilizing bootstrap-vue.js, I created a tab that looks like this: https://i.sstatic.net/EW76k.png The default color of the tab title doesn't fit with my project theme, so I attempted to change it. I found information on how to modify the tab title in ...

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

Issue with loading CSS and JavaScript following a GET request

I initially used express and the render function to display different pages on my website. However, I've now decided to switch to vanilla JavaScript instead. The objective is to load the HTML file along with all the necessary JS and CSS files. Below i ...

How can I incorporate checkboxes and crosses for validation in AngularJS?

I've been searching through the documentation for angularjs and online resources, but I can't seem to find any information regarding a specific aspect of form validation. You know when you input something in a form field (like a name, phone numbe ...

Exploring the Various Path Options in Angular 2 Routing

As a newcomer to Angular and Node JS, I am currently working on an application and struggling with how to efficiently navigate between my different components. Users can input the name of a user and add books associated with them When clicking on a book ...

Maintain the background div while scrolling horizontally

I am facing an issue with my wide bar chart where I use iScroll to enable horizontal scrolling. Behind the bar chart, there are horizontal lines that should move along in the background as the user scrolls horizontally. The challenge is to keep the lines v ...

Cutting imagery to create a new design element

https://i.sstatic.net/IAh0h.jpg There is an image above with 6 gears (circles with pointy edges). My goal is to separate them into individual pictures and, on each picture's hover, have a relevant line with text appear. How can I achieve this? The a ...

Excluding specific e2e tests in Protractor: A guide

I have a collection of end-to-end tests for my AngularJS web application. Here is the configuration in my current protractor.config.js file: // __dirname fetches the path of this specific config file // assuming that the protractor.conf.js is located at t ...

Is using window.postMessage(...) a viable option for facilitating cross domain file uploads?

I'm wondering if there is a way to achieve cross domain file upload using window.postMessage(...) or any other technique. Can anyone help with this? ...

Creating static websites through dynamic processes

I am currently developing a website generator using React, Express/Node, and MongoDB. The process involves creating a user interface to collect content and styling parameters through a multi-step form, followed by a dashboard for users to manage settings. ...

Having difficulties testing the Angular HTTP interceptor with Karma and Jasmine

Testing an http interceptor has been quite the challenge for me. Despite having my token logged in the console and ensuring that the request URL matches, I still can't figure out why it's not working with the interceptor in place. Interestingly, ...

Examine the spans and delete the first-child node

Basically, this functionality allows the user to cycle through hidden information by clicking on it. Here is how you can structure your HTML: <div id="facts"> <span>click to cycle</span> <span>fact 1</span> <s ...

Having trouble retrieving data from the MongoDB database using Node.js

Having trouble with data retrieval from MongoDb Successfully connected to MongoDb, but when using the find command, it should return an empty collection, yet nothing is being returned. What could be causing this issue and how can it be monitored through ...