Accessing the menu

There are two main headings in my menu: Administration and Market

https://i.sstatic.net/JbePq.png

When I click on the Administration heading, submenus for Portfolio and Corporate Action are displayed

https://i.sstatic.net/oyabv.png

The issue I am facing is that if I then try to open the Market section, the Administration submenu remains visible.

https://i.sstatic.net/Df95M.png

I want to ensure that only one menu can be open at a time.

<ul class="nav-links" *ngFor="let menu of menus; let i = index">
   <li [ngClass]="{ selected: selectedTab === menu.route }">
      <a routerLink="{{ menu.route }}" routerLinkActive="active" (click)="toggleMenu(i); selectedTab = menu.route">
         <i class="{{ menu.class }}"></i>
         <span class="links_name"> {{ menu.item }} </span>
         <i class="{{ menu.arrowDown }} iconArrow" *ngIf="selectedTab !== menu.route || !showSubmenu[i]"></i>
         <i class="{{ menu.arrowUp }} iconArrow " *ngIf="selectedTab === menu.route && showSubmenu[i]"></i>
      </a>
   </li>
   <ng-container *ngFor="let submenu of menu.submenus; let j = index">
      <li *ngIf="showSubmenu[i]">
         <a routerLink="{{ submenu.route }}">
            <i class="{{ submenu.class }}"></i>
            <span class="links_name"> {{ submenu.item }} </span>
         </a>
      </li>
   </ng-container>
</ul>

and

export class DashboardComponent implements OnInit {

    selectedTab: string;

    showSubmenu: any[] = [];

    menus: any[] = [

        /* Administration */
        {
            class: 'bx bx-lock-alt',
            item: 'Administration',
            route: '/dashboard/administration',
            arrowDown: 'bx bx-chevron-down',
            arrowUp: 'bx bx-chevron-up',

            submenus: [{
                    class: 'bx bx-key',
                    item: 'Portfolio',
                    route: '/administration/portfolio',
                },
                {
                    class: 'bx bx-wallet',
                    item: 'Corporate Action',
                    route: '/administration/corporate-action',
                },
            ],
        },



        /* Market */
        {
            class: 'bx bx-chart',
            item: 'Market',
            route: '/dashboard/market',
            arrowDown: 'bx bx-chevron-down',
            arrowUp: 'bx bx-chevron-up',

            submenus: [{
                    class: 'bx bx-coin-stack',
                    item: 'Value',
                    route: '/market/value',
                },
                {
                    class: 'bx bx-line-chart',
                    item: 'Indice',
                    route: '/market/indice',
                },

            ],
        },

    ];

    constructor() {}

    ngOnInit() {}


    toggleMenu(index: number) {
        this.showSubmenu[index] = !this.showSubmenu[index];
    }

}

You can find the complete code here

Answer №1

To begin, remove the showSubmenu feature and instead, introduce a new property within menus:

        {
            class: 'bx bx-lock-alt',
            item: 'Administration',
            route: '/dashboard/administration',
            arrowDown: 'bx bx-chevron-down',
            arrowUp: 'bx bx-chevron-up',
            isOpened: false // newly added property

        },

Within the toggleMenu function, iterate through the menus array and set all isOpened values to false initially. Then, update the isOpened property of the last clicked menu item to true as follows: menu[index].isOpened = 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

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Encountering CORS policy block when attempting to post data using Geoserver API through Angular

I'm currently working on Angular and I need to integrate the Geoserver API to publish spatial database data. Previously, I successfully used PHP Curl with the API and now I want to incorporate it into my Angular app. It's worth mentioning that ...

The information is not visible on Azure Portal

After completing the integration, I am still unable to view the appropriate logs in Azure Portal. I have carefully followed the instructions provided at I am looking to see all the details in Azure Portal such as username, current URL, and name. Do I nee ...

Steps for incorporating lazy loading into a multi-level application

Having difficulties with the architecture of my 3-tier application. Example urls: / (base url) dummy-configuration/ dummy-configuration/dummyModel dummy-configuration/dummyModel/dummyData Consists of a dummy config module, an dummyModel module, and a d ...

Dynamically change or reassign object types in TypeScript

Check out the example you can copy and test in TypeScript Playground: class GreetMessage { message: {}; constructor(msg: string) { let newTyping: { textMsg: string }; // reassign necessary this.message = newTyping; this.message.textMsg = msg; ...

Develop a personalized Angular module utilizing ngx-translate functionality

I recently developed my own personal Angular library filled with various components to streamline my projects. I followed a helpful tutorial to create the library successfully. Testing it in another project went smoothly. Now, the challenge is incorporati ...

Implementing routerLinkActive for the same link in multiple sections in Angular

I am facing an issue with the routerLinkActive class in my application. I have two sections, one for pinned tools and one for all tools. Both sections have the same routerLink defined. The problem is that when I click on a link in the pinned tools section, ...

Incorporating redux-offline seamlessly into your Angular 5 project

I'm currently grappling with the decision of how to develop an Angular web application that can function seamlessly under offline conditions. While researching possible solutions, I came across react-offline which seems to be a reliable choice for ha ...

CSS: Placing items within an ng-for loop utilizing the "fixed" position property

<ul class="nav nav-pills nav-stacked" style="list-style: none"> <li *ngFor="#el of dragZoneElems; #idx = index"> <h4 style="position: fixed; top:'idx'*10" [dragResponder]="el">{{el.first}} {{el.last}}</h4& ...

Is it possible to use @ViewChild to target an element based on its class name?

The author of this article on Creating Advanced Components demonstrates selecting an element by creating a directive first: @Directive({ selector: '.tooltip-container' }) export class TooltipContainerDirective {} Then, the author uses this d ...

Angular 12: TypeScript Issue TS2339 - Unable to Locate Property on Type

Whenever I use the code below, I encounter error TS2339: Property 'timestamp' does not exist on type 'LogRepair[]' In the component's HTML file, I am attempting to loop through an array of properties defined in the LogRepair typ ...

Can you tell me how to add a custom CSS class to a cell in ag-grid using Angular?

I am facing a challenge with applying CSS to cells in ag-grid in Angular based on specific logic. I have assigned an object to the grid, where one of the fields contains a value for Object.hours and I need to apply styling based on the Object.status proper ...

The array has unexpectedly condensed to contain only a single element, rather than its original three

Whenever I fetch data from a server, I use promises to wait for the data to arrive. However, I recently encountered an unusual situation where, upon navigating back and forth between pages, the tasks array contains three SelectedCustomerTasks elements when ...

Error in Next.js only occurs during the production build when using styled components, tailwind CSS, and twin styling

After successfully building my application in development mode, I encountered an error when attempting a production build. The error appears on the image linked below: https://i.stack.imgur.com/sNr2v.png I suspect that the issue lies within the _document ...

On a mobile device, the keyboard is hiding the PrimeNG dropdown

While my dropdown works flawlessly on a desktop browser, I encountered an issue when accessing it on an Android device. The dropdown immediately disappears and the virtual keyboard pops up, which is not the case on iOS devices. I suspect that the problem ...

Typescript: How can we determine the data type of React Router Link?

Trying to pass Link from react-router-dom as props and needing to specify it in the interface. While hovering over the Link element, the type displayed is: React.ForwardRefExoticComponent<LinkProps & React.RefAttributes<HTMLAnchorElement>> ...

Is it possible to overlook specific attributes when constructing an object using TypeScript interfaces?

I have defined an interface with various properties. I am looking to instantiate an object based on this interface, but I only want to partially initialize some of the properties. Is there a way to accomplish this? Thank you. export interface Campaign { ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

Reloading the current route in Angular 4 using routerLink

Is it possible to refresh the current page by clicking on a link using routerLink? An example of the menu structure I have is: <ul> <li><a routerLink="home">Home</a></li> <li><a routerLink="users">Users</a& ...