How can I detect click events on SVG path element using Angular?

Is it possible to detect click events on SVG elements such as path or g using Angular?

To see an example of this, check out this demo. Right now, if a (click) event binding is added to the svg elements, the click() event handler will trigger. However, how can we make it work for path or g svg elements?

The main objective here is to assign a class to the path element when it is clicked by the user.

Answer №1

The example provided by the original poster demonstrates how to listen for click events on an SVG element using Angular. To simplify, here is what the main.html file could look like:

<svg width="500" height="500" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <path 
     (click)="click($event)"
      style="fill: none; stroke: #000000; stroke-width: 1px;"
      d="M 10.280374,48.130842 V 26.168224 H 52.336448 V 70.794392 H 26.869158 V 50 h -7.476635"
    />
</svg>

I have included the original poster's code for main.ts from StackBlitz so that others can test it later:

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  templateUrl: `./main.html`,
})
export class App {
  name = 'Angular';
  click(e: MouseEvent) {
    console.log('DING DONG', e.target);
  }
}

bootstrapApplication(App);

This setup will ensure that e.target points to the correct path element when clicked.

If you are encountering issues with the clickable area of the element, the problem lies elsewhere. When there is no fill present (due to fill:none in CSS), clicking is limited to the stroke. In cases where the stroke is thin, clicking becomes difficult.

To resolve this issue without compromising performance, you can add the CSS property pointer-events: all to the path element. (For more information on this property, refer to https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events)

For older browser support, you can use fill: rgba(0,0,0,0) or fill: transparent, or apply any fill color with fill-opacity: 0. Keep in mind that this may impact performance slightly as the browser may still attempt to paint a 'transparent color' layer over the background in those areas (even though the end result is the same – not painting over the background).

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

store JSON data within an HTML list element

I've been working on a JavaScript script that allows me to generate list items in HTML. Right now, I have functionality to drag and remove the items using another script. However, I am interested in adding some additional information to each list item ...

Tips for implementing a search filter in a select dropdown menu using Angular

I am attempting to enhance my select option list by including a search filter. With numerous options available, I believe that having a search function will make it easier for the user to locate their desired selection. I hope my message is clear despite ...

Having trouble receiving error messages in Angular 2

In my AuthService, an error message is being thrown as a Business Error. When this error is caught in my LogInComponent, instead of displaying the error message "Login failed Error", it shows "Type object Object" in the console log. Why is this happening a ...

Exploring methods to deactivate specific dates within the angular material datepicker

Is it possible to prevent specific dates from being selected based on the current date? For example, if today is 8/1/16, I would like to disable the next 4 days (any number of days could be chosen), excluding weekends. So, if today is 8/1/16, I would want ...

Tips for sending a structured search query to the findOne() function in MongoDB with Node.js

I have a Restful service built with node.js that takes user input to create a query string for MongoDB. However, whenever I try to pass this query to findone() in MongoDb and call the service, it displays a "query selector must be an object" message in the ...

Modify the color of the text input by the user in an AJAX-enhanced text box

After successfully implementing an autocomplete textbox using AJAX Autocomplete, I decided to enhance the feature with some Fuzzy logic. Now, as the user enters 3 characters, my database returns a list of records that match those characters. The search re ...

Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried runni ...

Fixed-sized array containing union parameters

One of my programming utilities allows me to create a statically sized array: export type StaticArray<T, L extends number, R extends any[] = []> = R extends { length: L; } ? R : StaticArray<T, L, [...R, T]>; To verify its functionality, ...

Tips for utilizing a particular field in a JSON object as the data origin while employing ng2-completer

As a newcomer to Angular and ng2 completer, I am working with an array of objects structured like this: var concepts = [ { id:, code:, concept:, display: } ............ ] The goal is to have the data source for auto suggest feature as the di ...

PHP: Establishing SESSION Variables

On Page1.php, there is a variable called "flag" with the value of 1. When clicked, it triggers the JavaScript function named "ajaxreq()" which will display the text "Click me" from an AJAX request originating from page2.php. If you click on the "Click me" ...

Achieving Bi-Directional Data Binding with Vue.js using the vue-property-decorator Library

Currently, I am working with Vue.js and TypeScript while also utilizing the vue-property-decorator. My goal is to establish two-way data binding between a parent and child component. Below is an example of what I have in mind: Parent Component <templa ...

Transmit information from child to parent as needed using @input and @output in Angular 2

Is there a way to pass an object from child to parent without relying on @viewChild or services? export class MultiSelectComponent implements OnInit { selectedItems: FormSelectComponentOption[] = []; @Input() items: FormSelectComponentOption[]; @Output ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

The HTML 5 video is not functioning properly on an iPad, and the layout of the iPad has black areas on the sides

Having some trouble with an HTML 5 project where the video plays on Chrome and Safari PC browsers but not on iPad. The task at hand is to get it working in portrait mode only, with the video playing when tapped/clicked. <!doctype html> <!--[if ...

Creating a navigational sidebar with dynamic responses using Angular 8

Currently, I am working on creating a responsive sidenav USING ANGULAR WITHOUT MATERIAL DESIGN. My goal is to achieve the same level of responsiveness that can be seen on https://angular.io. Within my project, I have created separate components for the top ...

What is the best way to implement custom sorting for API response data in a mat-table?

I have been experimenting with implementing custom sorting in a mat-table using API response data. Unfortunately, I have not been able to achieve the desired result. Take a look at my Stackblitz Demo https://i.sstatic.net/UzK3p.png I attempted to implem ...

The header location functionality is not functioning properly on the live server

I have a single registration and payment page where the program flow goes from registration to confirmation and then to payment. Upon validation and calculation on the registration page, it should redirect to the confirmation page. This is my code: < ...

Differences between using a getter in Vue.js/Vuex compared to directly accessing state values on the create lifecycle hook

As I utilize the created lifecycle hook within vue.js to fetch data from my store and pass it to a vue component's data, an interesting observation arises. When I employ this.selectedType = store.state.selectedType, the data is successfully retrieved ...

Using ThreeJs and TweenJS to insert a delay between tweens using a for loop

Struggling with animating a bin packing problem using Three.JS and Tween.JS. I am having difficulty getting the animation to play successively rather than all at once within my loop. Attempting to use the setTimeout solution has not been successful. Does a ...

The chosen options are not appearing. Could this be a problem related to AngularJS?

I am working on setting up a dropdown menu in HTML that includes only the AngularJS tag. This dropdown menu will be used to populate another AngularJS dropdown menu. Below is the code for the first dropdown menu: <select class="form-control" ng-model=" ...