angular - Angular 等价于事件目标匹配
问题描述
我正在尝试将下拉菜单从 Javascript 转移到 Typescript 以在我的 Angular 项目中使用。我不知道如何模拟 event.target.matches,这给我带来了一些问题。是否有易于实现的 Typescript 等价物?
这是组件代码:
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');
}
}
}
}
}
这给了我错误:“[ts] 属性 'matches' 在类型 'EventTarget' 上不存在。” (由 onClickedOutside 的 if 语句触发。
编辑,模板代码:
<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>
解决方案
也许你使用的是旧版本的 TypeScriptmatches
元素上的方法是在较新版本的 TypeScript 中实现的。您可以看到引用该问题的这个github 线程。
要解决它:
- 更新到最新版本的 TypeScript
或者
- 您可以更改您的条件
matches
并classList.contains()
改用。
if(!e.target.classList.contains('dropbtn'))
推荐阅读
- jasper-reports - 如何在 excel 导出中冻结第二张工作表的第一行?
- linux - 如何使用完整命名的布尔标志运行 linux shell 脚本?
- javascript - 由`pointerdown`调度的`blur`事件是否保证在用户计划的任务之前触发?
- amazon-web-services - 使用 Cognito 进行 Web 应用身份验证和 S3 访问,无需嵌入密钥和访问密钥
- angular - Angular Transition 前进时有效,但后退时无效
- elasticsearch - 如何找到与不同查询中的所有单词匹配的文档?
- json - 使用 jq 将管道文件转换为 json 并插入标签
- linux - 外部调用的时间命令
- database - 在 Influx 查询中显示倒数第二个项目(或忽略最后一个)
- python-asyncio - 异步函数何时返回其值