Matching event targets in Angular

I am in the process of transitioning a dropdown menu from Javascript to Typescript for utilization in my Angular project. I am facing challenges as I cannot find a way to replicate event.target.matches appropriately. Is there an alternative in Typescript that is simple to integrate?

Below is the component code:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Test Site Please Ignore';
  currentUser: any;

  ngOnInit() {
    this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
  }

  dropFunction(variable) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
      }
    }
    var thisElement = document.getElementById(variable);
    thisElement.classList.toggle("show");
  }

  onClickedOutside(e: Event) {
    if (!e.target.matches('.dropbtn')) {
      var dropdowns = document.getElementsByClassName("dropdown-content");
      var i;
      for (i = 0; i < dropdowns.length; i++) {
          var openDropdown = dropdowns[i];
          if (openDropdown.classList.contains('show')) {
              openDropdown.classList.remove('show');
          }
      }
    }
  }
}

This results in the error message: "[ts] Property 'matches' does not exist on type 'EventTarget'." (triggered by the if statement within onClickedOutside).

Additionally, here is the template code:

<div class="dropdown">
<button (clickOutside)="onClickedOutside($event)" (click)="dropfunction('myDropdown0')" id="dropbtn0" class="dropbtn">Home</button>
<div id="myDropdown0" class="dropdown-content">
    <a routerLink="/"> Index </a>
    <a routerLink="/profile">Profile</a>
    <div *ngIf="currentUser">
      <a routerLink="/login">Logout</a>
    </div>
    <div *ngIf="!currentUser">
      <a routerLink="/login">Login</a>
      <a routerLink="/register">Register</a>
    </div>
</div>

Answer №1

It's possible that an outdated version of TypeScript is causing the issue. The matches methods on elements are available in newer versions of TypeScript. You can find more information in this GitHub thread.

To resolve this:

  • Upgrade to the most recent version of TypeScript

Alternatively,

  • You could adjust your condition by replacing matches with classList.contains().
 if(!e.target.classList.contains('dropbtn'))

Answer №2

Consider utilizing

if( e.target.value !== '.dropbtn')

as an alternative.

Answer №3

Managed to figure it out thanks to this helpful post. Just needed to assign event.target to an element.

Solution in action:

onClickedOutside(e: Event) {
var ele=<Element>e.target;
if (!ele.matches('.dropbtn')){
  var dropdowns = document.getElementsByClassName("dropdown-content");
  var i;
  for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
          openDropdown.classList.remove('show');
      }
  }
}

}

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

Troubleshooting Angular error encountered during the execution of the 'ng build --prod' command

While developing my Angular application, I encountered an issue when using the ng build --prod command. Surprisingly, everything was working fine with ng serve. I am struggling to figure out what the problem could be. ERROR in: Unable to locate resource a ...

Issue with the naming of Angular button conflicting with array naming conventions

I'm encountering a challenge with button naming in my Angular SPA component that I'm currently developing. Background - On a page where a data table is displayed, there's a 'Select' control that allows users to choose which column ...

Encountering a TypeScript error while generating a sitemap in an array within Next.js 14

Recently, I created a sitemap.tsx file within the app router in NextJS 14. However, I encountered an issue when attempting to create an array of routers as shown below: const contacts = NavContacts?.filter((val) => { if ( !val.name.inc ...

Launching superheroes application developed with Angular 2

I followed the heroes tutorial and customized my own Angular2 application using some components. Although it resembles the heroes tutorial, I have successfully set up everything with my IDE and npm. Now, I am facing challenges in deploying my application i ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Utilizing Enum Lowercase as Index Key Type in TypeScript

Is there a way in TypeScript to use the lower case of an enum as an index key type? I have an enum defined as: export enum NameSet { Taxi = 'Taxi', Bus = 'Bus', Empty = '', } I want to define an object with keys based o ...

What is the reason behind the failure of a react factory method compilation when extending a typescript class, despite it working perfectly fine on the base class?

As I delve into my lengthy codebase consisting of hundreds of lines, I have managed to narrow down my issue to a concise example. My query pertains to the peculiar behavior exhibited by the Typescript compiler in a specific scenario. The snippet below com ...

Form: Initiate a manual valueChange

Currently, I am in the process of constructing a form using FormBuilder. My goal is to invoke another function whenever one of my FormControl elements is updated. To achieve this, I have opted to utilize valueChanges. However, I am facing an issue where I ...

Avoid using propTypes for props verification

Looking for a solution to handle multiple props on a button: interface buttonProps { secondary?: boolean; tertiary?: boolean; width?: number; children?: any; icon?: string; } If the button includes an icon without any children, how can ...

Selecting dropdown list values with Selenium in C#

I'm encountering an issue while trying to populate a dropdown list using Selenium WebDriver in C#. Below is the snippet of HTML code: <div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 278px;" tit ...

Dynamic row generation with dropdown menu and data binding

Currently, I am working with a table that dynamically creates rows containing details of uploaded files. Each row includes a dropdown menu for selecting the file type. The issue I am encountering is with the dynamically generated dropdown menus. If I sele ...

Using TypeScript and JQuery: handler event does not possess the properties 'target' and 'currentTarget'

I encountered the following error message: TS2339: Property 'target' does not exist on type 'Event'. while working with this code snippet: this.$Element.on('click', SELECTOR, (event: JQuery.Event) => { const $ClickedLi ...

Sending file URL to Angular component

Hey there, I am looking to relocate an existing link within my Angular 4 project. For instance, the link I want to move is "". I have attempted to do so in my router configurations: path: 'test', component: TestComponent, children: ...

Customize drawerLabel in React Native based on user's current location

I am facing an issue with my react-native application where I need to dynamically render a menu item based on the user's location. However, since the function that fetches the user location is asynchronous, I am encountering an undefined error. My que ...

Steps to trigger a modal using an effect and automatically close it upon receiving a specific dispatched action

Is there a better way to handle the closing of a dialog after a specific action is dispatched? Currently, I have a CalendarEventDeleteDialog with "yes" and "no" options. If the user selects "yes," a CalendarEventDeleteAction is dispatched followed by a Cal ...

How to specify the file path for importing a custom module?

I am currently learning Angular 2 and encountering an issue with importing a custom module that contains interface declarations. Here is my folder structure: https://i.stack.imgur.com/heIvn.png The goal is to import product.interface.ts into a component ...

Function that sets object properties based on specified keys and verifies the value

Let's consider a scenario where we have an object structured like this: interface Test{ a: number; b: string; c: boolean; } const obj:Test = { a: 1, b: '1', c: true, } We aim to create a function that can modify the value ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...

filter failing to provide output

Issue with fetching partnername from the filter function, always returning undefined. administrationList = [ { "runid": 6, "partnerid": 2, "partnername": "test admin2", }, { "runid& ...

Pusher: Signature is invalid: The expected digest for HMAC SHA256 is not in hexadecimal form

When I tried to subscribe to a private Pusher channel, I encountered the following error message: Invalid signature: The expected HMAC SHA256 hex digest of 124425.1545539:private-dash-98, was e7ed825903c1e18931cceebba457270a6b1e79331387527ab97e430ba4d220 ...