代码之家  ›  专栏  ›  技术社区  ›  Marcus Grass

与事件目标匹配的角度等效

  •  0
  • Marcus Grass  · 技术社区  · 8 年前

    以下是组件代码:

    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');
              }
          }
        }
      }
    }
    

    编辑,模板代码:

    <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>
    

    3 回复  |  直到 6 年前
        1
  •  2
  •   edkeveked    7 年前

    也许你使用的是旧版本的打字脚本 这个 matches 元素上的方法在较新版本的TypeScript中实现。你可以看到这个 github thread

    要解决这个问题:

    • 更新至TypeScript的最新版本

    • 你可以改变你的状况 和使用 classList.contains() 相反
     if(!e.target.classList.contains('dropbtn'))
    
        2
  •  0
  •   Lynx 242    8 年前

    尝试使用

    if( !e.target.value === '.dropbtn')
    

        3
  •  0
  •   Marcus Grass    8 年前

    解决了 with the help of this post

    onClickedOutside(e: Event) {
    var ele=<Element>e.target;
    if (!ele.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');
          }
      }
    }
    

    }

    推荐文章