我是Typescript的新手,因为尝试使用Angular。我正在将项目重写为角度系统。而且我遇到了一个问题。当用户单击下拉按钮以外的任何位置时,我想删除下拉内容。请帮助这个初学者,我一直在谷歌搜索,但一无所获。非常感谢!
详细信息
这些在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 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)
我如何在JAVASCRIPT中使用它(作品)
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");
}
}
}
应该是$ event而不是$ events。
尝试一下:
@HostListener('document:click', ['$event'])
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");
}
}
}