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>