How to close a dropdown on click outside with Angular?

Sometimes, we want to close a dropdown on click outside with Angular.

In this article, we’ll look at how to close a dropdown on click outside with Angular.

How to close a dropdown on click outside with Angular?

To close a dropdown on click outside with Angular, we can use the nativeElement.contains method.

For instance, we write

@Component({
  host: {
    "(document:click)": "onClick($event)",
  },
})
class SomeComponent {
  constructor(private _eref: ElementRef) {}

  onClick(event) {
    if (!this._eref.nativeElement.contains(event.target))
      // ...
      doSomething();
  }
}

to create the SomeComponent component.

We make the component run the onClick method when we click on anywhere on the page with

@Component({
  host: {
    "(document:click)": "onClick($event)",
  },
})

And then we check !this._eref.nativeElement.contains(event.target) to make sure the click is outside of the current element before we call doSomething.

Conclusion

To close a dropdown on click outside with Angular, we can use the nativeElement.contains method.