Ways to activate a click event on a parent div without affecting a particular child element in Angular

I am working on an Angular component that consists of nested div elements. My goal is to trigger a click event on the parent div, however, I want to ensure that if the menu child div is clicked, the parent div's click event should not be triggered.

Check out the demo here!

main.ts

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div (click)="openAlert()" class="parent">Parent
      <div class="menu">Menu</div>
      <div class="child child-2">Child 2</div>
      <div class="child child-3">Child 3</div>
    </div>
  `,
})
export class App {
  name = 'Angular';

  public openAlert() {
    alert('Details View');
  }
}

Answer №1

To prevent event bubbling to the parent element, you can utilize the event.stopPropagation() method within the click event handler for the "menu" div.

Here is an example of how you can implement this in your code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div (click)="openAlert()" class="parent">Parent
      <div (click)="stopPropagation($event)" class="menu">Menu</div>
      <div class="child child-2">Child 2</div>
      <div class="child child-3">Child 3</div>
    </div>
  `,
})
export class App {
  name = 'Angular';

  public openAlert() {
    alert('Details View');
  }

  public stopPropagation(event: MouseEvent) {
    event.stopPropagation();
  }
}

Answer №2

When handling a click event, you have the ability to check if the target of the click is within the parent div and not one of its child divs. In this example, I added a menu-wrapper around the child divs for easier understanding.

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div class="parent" (click)="onClick($event)">
      Parent
      <div class="menu-container">
        <div class="menu">Menu</div>
        <div class="child child-2">Child 2</div>
        <div class="child child-3">Child 3</div>
      </div>
    </div>
  `,
})
export class App  {
  name = 'Angular';

  protected onClick(ev: MouseEvent): void {
    // checking if the target is within parent div but not menu-container div
    const shouldShowAlert =
    ev.target instanceof HTMLElement && !!ev.target.closest('.parent') && !ev.target.closest('.menu-container')

    if (shouldShowAlert) {
      this.openAlert();
    }
  }

  public openAlert() {
    alert('Details View');
  }
}

For more information on the closest method, visit here.

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

Finding the Text of an HTML Element

I need to retrieve the text content from an HTML element. For example, if I have <p>ABCD</p> I want the output to be ABCD It would look something like this: var html='<p>ABCD</p>'; var str = extractText(html); I belie ...

API endpoint generating a Vue component as a rendered output

In the process of developing a document templater service, I am faced with the challenge of handling numerous document templates (contracts, protocols, etc.) written in Vue. The concept revolves around clients sending props in the body, which are then pass ...

The element 'imgAreaSelect' does not appear to be valid in this context

I came across an example, but it is not specifically for Angular. I attempted to create a project in angular 6 involving image area selection, but encountered the following error: .component.ts(64,16): error TS2339: Property 'imgAreaSelect' do ...

What are the steps to deploy a React, Next.js, and Express.js application on Netlify?

I am currently in the process of deploying my application to Netlify, featuring a combination of React, Next.js, and Express.js. While there are no errors showing up in the Netlify console, unfortunately, the site is not live as expected. https://i.stack ...

I encountered an error while conducting an Angular test - Failed: Unable to access the property 'className' as it is undefined

My spec.ts file is running fine with all test cases passing, but occasionally I encounter failures with the error message Failed: Cannot read property 'className' of undefined. This error seems to be related to the Syncfusion library I am using f ...

Create a fresh type by dynamically adjusting/filtering its attributes

Suppose we have a type defined as follows: type PromiseFunc = () => Promise<unknown>; type A = { key1: string; key2: string; key3: PromiseFunc; key4: string; key5: PromiseFunc; key6: SomeOtherType1[]; key7: SomeOtherType2[]; key8: ...

What is the best method for creating a draggable widget in HTML, specifically with the use of Angular?

I am searching for an HTML div that is free floating and can be dragged and positioned anywhere on the page without being affected by other elements. It's okay if the element blocks the view of elements below, and it would be great if there is a minim ...

Utilizing X-editable and Parsley to trigger dual Ajax calls

Here is a snippet of code I am working with: $.fn.editable.defaults.mode = 'inline'; var editable = $('.x-editable').editable({ send: 'always', validate: function() { var form = editable.next().find('form ...

What is the process for conducting linting with nodemon?

Is it possible to utilize nodemon for linting my javascript without the use of build tools like gulp or grunt, in order to fully leverage node and npm? Nodemon's output can be piped. I am interested in using this feature for linting the changed file ...

The issue of overwritten callbacks is occurring due to the use of multiple .use() functions on the

Utilizing a module known as consign, I am able to conveniently include multiple modules from a directory all at once, eliminating the need for numerous require statements. In my code, I have set the mount path for each endpoint at the beginning of the rout ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

What is the best way to display multiple files in a vertical stack when choosing a file?

<div class="selected-file-container align-items-center justify-content-between d-none"> <div class="selected-file d-flex align-items-center"> <img id="selectedImage" class="hidden" src="&qu ...

Using Angular 2 to efficiently recycle a subcomponent with the same form across multiple parent components while maintaining its state

I've been struggling to find someone with the same issue as me, even though the title may seem familiar. Perhaps I need help rephrasing my question? Here's an explanation: Use case: I have multiple routes (only 2 in the example below) set up fo ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...

Tips for creating a script that is compatible with both Java and C++

We currently offer both Java and C++ versions of our distributed messaging system product. I am in the process of developing a framework to conduct system testing across multiple servers. In order to accomplish this, I need a "test coordinator" process th ...

Best practice for stopping routing in angular

I am currently working on an angular application that includes guest functionality. This feature allows me to create a guest account for all unauthorized users in the background. I need to pause routing until the guest account is created and then specify a ...

Adding an item to an array in AngularJS: A step-by-step guide

Here is a snippet of code I have been working on: $scope.studentDetails=[]; $scope.studentIds={}; $scope.studentIds[0]{"id":"101"} $scope.studentIds[1]{"id":"102"} $scope.studentIds[2]{"id":"103"} Within the above code, when I select student ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

What is the best way to divide an array while extracting data from a JSON object using

Currently, I am parsing the json data. My goal is to find a specific property within the json object that contains two nested arrays (list and array). However, when extracting the values, they are all being stored in a single array. Is there a way to separ ...

What is the process for ordering by a many-to-many relationship in Sequelize?

I am dealing with a many-to-many relationship between User and Category, connected through the UserCategory model. Here is the code snippet illustrating this relationship: let user = await User.findAll({ where: { id: req.query.user }, attribut ...