Collapse all Angular Sidemenu subitems at once

I have a Sidemenu with items and subitems. Currently, the subitems open by default but when I close one, it closes all the items together. I want to modify it so that only that specific item closes. The reopening functionality is working fine but I need the closing behavior to be the same.

Here is my HTML code:

<ng-container *ngIf="!item.hidden">
  <li *ngIf="themeLayout === 'vertical'" data-username="dashboard Default Ecommerce CRM Analytics Crypto Project"
    class="nav-item pcoded-hasmenu ng-tns-c20-2 ng-star-inserted pcoded-trigger" [routerLinkActive]="['active']">
    <a [routerLinkActive]="['active']" href="javascript:" class="nav-link" (click)="navCollapse($event)">
      <ng-container *ngTemplateOutlet="itemContent"></ng-container>
    </a>
    <ng-container *ngTemplateOutlet="subMenuContent"></ng-container>
  </li>

...

component.ts

@Component({
  selector: 'app-nav-collapse',
  templateUrl: './nav-collapse.component.html',
  styleUrls: ['./nav-collapse.component.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)', display: 'block'}),
        animate('250ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('250ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ],
})
export class NavCollapseComponent implements OnInit {
  ...
}

Preview:

https://i.sstatic.net/tRZ4U.gif

Answer №1

To prevent the close event from bubbling up to all menus, simply use stop propagation within your event handler.

In your HTML code, add this snippet to your menu:

(click)="onEvent($event)"

Then in your TypeScript code:

onEvent(event) {
   event.stopPropagation();
}

Alternatively, you can do:

(click)="navCollapse($event); event.stopPropagation();"

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

What is the best way to alter an Rxjs event in order to track pressed keys?

I found a helpful solution for hotkeys using this RXjs method. In my setup, I am using the condition below to detect leftShift + m keys: const toggle$ = shortcut([KeyCode.ShiftLeft, KeyCode.KeyM]); The issue I'm facing is that it only triggers when ...

The value of "metadata" is not a valid export entry for Next.js

After I installed Next.js 14 with TypeScript, I encountered an error related to my metadata type definition. import type { Metadata } from "next"; export const metadata: Metadata = { title: "next app", description: "next app 1 ...

Issue with BehaviorSubject<Object[]> causing incorrect array data upon initial subscription

I am facing an issue with a BehaviorSubject where the first .subscribe callback is returning an Array with 6 Objects. Strangely, in console output, it shows length: 6, but every for-loop I iterate through the array only runs 5 times and even when I log arr ...

Angular is having trouble with the toggle menu button in the Bootstrap template

I recently integrated this template into my Angular project, which you can view at [. I copied the entire template code into my home.component.html file; everything seems to be working fine as the CSS is loading correctly and the layout matches the origina ...

Navigating TS errors when dealing with child components in Vue and Typescript

Recently, I encountered an issue where I created a custom class-based Vue component and wanted to access its methods and computed properties from a parent component. I found an example in the Vue Docs that seemed to address my problem (https://v2.vuejs.org ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

The operation to append in Angular/Mutation was unsuccessful because parameter 2 is not a valid type of 'Blob' for FormData

Currently, I have set up my project with Angular/Apollo (Graphql) on the client side and NestJS on the server side. When it comes to uploading files to the server, I am utilizing the 'graphql-upload-ts' package for this task. Interestingly, the ...

Setting default selections for mat-select component in Angular 6

I've been attempting to preselect multiple options in a mat-select element, but I haven't been successful so far. Below is the snippet of HTML code: <mat-dialog-content [formGroup]="form"> <mat-form-field> <mat-select pla ...

Sign up for the observable, retrieve the asynchronous mapped outcome with input from the dialog, and then utilize the outcome from the map

Currently, I am utilizing an API-service that delivers an Observable containing an array of elements. apiMethod(input: Input): Observable<ResultElement[]> Typically, I have been selecting the first element from the array, subscribing to it, and the ...

Error encountered with tsc-generated .d.ts files stating "Namespace 'Jimp' not found"

Currently, I am in the process of developing an NPM package, and within my codebase lies a specific class that looks like this: import { MIME_PNG } from 'jimp'; import { IDimensions } from './spritesheet'; /** * Representing a single ...

Angular2's local variable determines the action being taken

Is there a way to disable a button based on the value of a local template variable? Here is the code snippet I have - <input type="text" #name> <button [disabled]='name.value' (click)='getvalue()'>Demo</button> ...

When attempting to start the Azure Functions within a Nodejs Monorepo, the runtime fails with an error

My setup involves a nodejs typescript monorepo structured as follows: libraries/ lib1/ lib2/ package.json tsconfig.json web-api/ function1/ function.json index.ts function2/ function.json index.ts host.json package.json ts ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Encountering problem with Karma, Angular 7, and FontAwesome: Unable to attach 'icon' property to 'fa-icon' as it is not recognized

An issue arises when attempting to bind to 'icon' since it is not recognized as a property of 'fa-icon'. During the execution of this test within people.component.spec.ts import { async, ComponentFixture, TestBed } from "@angular/core ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

What is the best way to implement useAsync (from the react-async-hook library) using TypeScript?

Currently, I am utilizing react-async-hook to retrieve API data within a React component. const popularProducts = useAsync(fetchPopularProducts, []); The fetchPopularProducts() function is an asynchronous method used to make API calls using fetch: export ...

Compilation is unsuccessful due to absolute path failure

My repo, nx, contains a single project with multiple libs. In the main file, I import express from 'express' and other necessary modules. import express from 'express'; import http from 'http'; import { router } from 'sr ...

Testing Playwright - accessing variables from the .env file

I am currently working on a Playwright test script in TypeScript and I'm looking for a way to leverage variables from my .env file within the test. Does anyone know how this can be accomplished? ...