Just starting out with Typescript and diving into Angular, I am currently in the process of converting my project to the Angular system. However, I've hit a roadblock. I need to figure out how to close the dropdown content when the user clicks anywhere except the dropdown button. Any help for this beginner would be greatly appreciated. I've been searching online but haven't found a solution yet. Thanks in advance!
DETAILS
These are from the app.component
app.component.html
<section class="nav">
<div class="one-side-nav">
<a href="#" routerLink = "/"><img id="logo" src="assets/img/logoheaven.png"></a>
<a href="#" routerLink = "/catalog" id="framed">SOMETHING</a>
</div>
<div class="one-side-nav">
<a href="">SOMTHING</a>
<a href="">SOMETHING</a>
<a href=""><img src="assets/img/lists/notification.png"></a>
<div class="dropdown">
<img (click)="dropdown()" class="dropdown-btn" id = "dropdown-btn" src="assets/img/defaultimg.png">
<div id="dropdown-content" class="dropdown-content">
<div class="box-head-blue"></div>
<a href="#">dropdown</a>
<a href="#">dropdown</a>
<a href="#">dropdown</a>
<button style="border-radius: 0px 0px 10px 10px" id="logout-btn">dropdown</button>
</div>
</div>
</div>
</section>
app.component.ts
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
//COMPONENT LOGIC
export class AppComponent {
title = 'SPARK | Trang Chủ';
dropdown() {
document.getElementById("dropdown-content").classList.toggle("show");
}
@HostListener('document:click', ['$events'])
onDocumentClick(event: MouseEvent) {
if (!(event.target == document.getElementById("dropdown-btn"))) {
var dropdown = document.getElementById("dropdown-content");
if (dropdown.classList.contains("show")) {
dropdown.classList.remove("show");
}
}
}
}
ERROR IM GETTING
ERROR TypeError: Cannot read property 'target' of undefined at AppComponent.onDocumentClick (app.component.ts:19) at AppComponent_click_HostBindingHandler (app.component.ts:10) at executeListenerWithErrorHandling (core.js:21815) at wrapListenerIn_markDirtyAndPreventDefault (core.js:21857) at HTMLDocument.<anonymous> (platform-browser.js:976) at ZoneDelegate.invokeTask (zone-evergreen.js:399) at Object.onInvokeTask (core.js:41640) at ZoneDelegate.invokeTask (zone-evergreen.js:398) at Zone.runTask (zone-evergreen.js:167) at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:480)
HOW I HAVE IT IN JAVASCRIPT (works)
function dropdown() {
document.getElementById("dropdown-content").classList.toggle("show");
}
window.onclick = function(e) {
if (!e.target.matches(".dropdown-btn")) {
var dropdown = document.getElementById("dropdown-content");
if (dropdown.classList.contains("show")) {
dropdown.classList.remove("show");
}
}
}