简体   繁体   English

Angular clickOutside 指令不起作用

[英]Angular clickOutside directive not working

I made a div which shows itself depending on a bool (called "menu"), and I wanted to make it so if the user clicks outside of it, the bool changes and therefore, the menu is hidden.我制作了一个 div,它根据 bool(称为“菜单”)显示自己,我想这样做,如果用户在它之外单击,bool 会发生变化,因此菜单被隐藏。 I've read a post about this and I've searched a bit about it, and I found that this is already made by some users.我读过一篇关于这个的帖子,我搜索了一下,我发现这已经是一些用户制作的了。

I've tried installing this one , creating the file myself and pasting this code , or even changing the last one to this , but it won't work and I don't know why.我试过安装这个,自己创建文件并粘贴这个代码,甚至把最后一个改成这个,但它不起作用,我不知道为什么。

The html is the following: html 如下:

<!-- Menu tarea-->
  <ng-container *ngIf="menu">
    <div (clickOutside)="abreMenu(this.tareaMenu)" class="popup-menu">
      <p>formulario here</p>
      <hr>
      <div>
        <button (click)="borrarTarea(this.tareaMenu)"></button>
        <span>Borrar</span>
      </div>
    </div>
  </ng-container>

You don't have to worry about the "abreMenu()" function, that works just fine.您不必担心“abreMenu()”function,它工作得很好。

Both the new directive and the one installed are called the same, but there are no errors.新指令和安装的指令都被称为相同,但没有错误。 I don't know if I messed the imports up but I'm getting nothing.我不知道我是否搞砸了进口,但我什么也没得到。

NOTE: This html file belongs to a component within "MyModule", which is imported in "AppModule", and there I've imported the "ClickOutsideModule" since I'd probably want to use it globally through the app.注意:这个 html 文件属于“MyModule”中的一个组件,该组件在“AppModule”中导入,并且我已经导入了“ClickOutsideModule”,因为我可能想通过应用程序全局使用它。

Why isn't it working?为什么它不起作用? Thanks.谢谢。

Instead using the clickOutside directive you could use a HostListener inside your component:代替使用 clickOutside 指令,您可以在组件内使用 HostListener:

// somewhere inside your component
@HostListener('document:click', ['$event'])
  outsideClick(event: MouseEvent): void {
    this.abreMenu(this.tareaMenu)
  }

I just experienced this problem last week.我上周刚遇到这个问题。 My solution was that the directive had to be a part of the "other" module definition, because the component which used it, was contained in that other module.我的解决方案是该指令必须是“其他”模块定义的一部分,因为使用它的组件包含在该其他模块中。

I didn't try to test if the main app.module components(via the import of the other module) could access the directive, but the problem was solved for all components in that "other" module.我没有尝试测试主要的 app.module 组件(通过导入其他模块)是否可以访问该指令,但是该“其他”模块中的所有组件的问题都已解决。

It's just my opinion but I think Angular has some serious issues with it's module system, not to be confused with the JavaScript module system.这只是我的意见,但我认为 Angular 的模块系统存在一些严重问题,不要与 JavaScript 模块系统混淆。 Angular needs to adopt the JavaScript (only) module system going forward. Angular 需要采用 JavaScript(仅)模块系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM