当我在angular4中点击外面时关闭下拉菜单

时间:2017-11-13 07:25:37

标签: html css angular

我只是想在不使用指令的情况下点击外部关闭下拉列表。我很困惑怎么做。请帮助我。这是我的通知组件

这是我的notification.html代码

   <a class="cursor-pointer"  matTooltip="Notifications"  
   target="_blank" (click)="shownotification()">

<i class="fa-bell fa" ></i>
</a>

 <div class="notification-container" *ngIf = "notification">
  <div class="up-arrow"></div>
  <div class="header">
      <h4 style="padding-right:40px;">Notification</h4>
      <h4 style="padding-left:90px;padding-right:0px;"><span>3</span></h4>

  </div>

  <div class="all-notifications">
  <div class="notifications">
    <span><i class="fa fa-check-circle" aria-hidden="true" style="color:green;"></i></span> &nbsp;<span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
  </div>

  <div class="notifications">
      <span><i class="fa fa-clock-o" aria-hidden="true" style="color:rgb(37, 125, 226);"></i></span> &nbsp;<span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
    </div>

    <div class="notifications">
        <span><i class="fa fa-cog" aria-hidden="true" style="color:rgb(196, 73, 24);"></i></span> &nbsp;<span class="f_clr">Lorem Ipsum Dollar</span> <span class="f_clr right_text"><span>2</span></span>
      </div>

  </div>

这是我的notification.component.ts

 notification: boolean = false;

  constructor() { }

  ngOnInit() {
  }
  shownotification() {
    this.notification = !this.notification;
     console.log(this.notification);
    }

1 个答案:

答案 0 :(得分:0)

@HostListener('document:click', ['$event', '$event.target'])
public onClick(event: MouseEvent, targetElement: HTMLElement): void {
    if (!targetElement) {
        return;
    }

    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) { 
         this.closeDropDown()
    }
}

或者像这样使用clickoutside指令的任何实现: https://www.npmjs.com/package/angular2-click-outside

https://www.npmjs.com/package/ng2-click-outside