首页 > 解决方案 > 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>

标签: angulartypescriptdrop-down-menudom-events

解决方案


也许你使用的是旧版本的 TypeScriptmatches元素上的方法是在较新版本的 TypeScript 中实现的。您可以看到引用该问题的这个github 线程。

要解决它:

  • 更新到最新版本的 TypeScript

或者

  • 您可以更改您的条件matchesclassList.contains()改用。
 if(!e.target.classList.contains('dropbtn'))

推荐阅读