Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - 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. 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:

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

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.

Why isn't it working? Thanks.

question from:https://stackoverflow.com/questions/65646854/angular-clickoutside-directive-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead using the clickOutside directive you could use a HostListener inside your component:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...