简体   繁体   中英

Autoclose dropdown menu problem with ng-select

I'm trying to create a dropdown menu, that closes automatically when the user click outside of it. In this menu I added a ng-select component, but when I click on one of the options, the menu will close, because the dropdown panel of the ng-select is not inside the DOM when it is closed, is there any way to achieve what I want? The dropdown menu to not close when the user select a ng-option? Here there is an example of the problem: https://stackblitz.com/edit/angular-8m1ta5?file=src%2Fapp%2Fapp.component.ts

Here is the code that I use to keep track of the click of the user:

  @ViewChild('father', {static: false}) father;
  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
    const clickedInside = this.father.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this.dropdown = false;
    }
  }

#father identify the container of the dropdown menu.

---UPDATE---

I reached a solution, but maybe this is not very clean: https://stackblitz.com/edit/angular-gymhed I just added a new variable that is changed with a timeout of 500ms after the ng-select is closed, this way for 500ms after the ng-option is selected, the dropdown cannot be closed.

The Attribute [closeOnSelect]="false" should do the work. You will have to add it to the <ng-select> tag

So, from the stackblitz the code will become:

<ng-select placeholder="Status" [closeOnSelect]="false">
        <ng-option [value]="'0'">Option 1</ng-option>
        <ng-option [value]="'1'">Option 2</ng-option>
        <ng-option [value]="'2'">Option 3</ng-option>
</ng-select>

Here you can find the documentation https://github.com/ng-select/ng-select

binding the isOpen property of ng-select to your components dropdown flag should do the trick:

<ng-select placeholder="Status" [isOpen]="dropdown">
    <ng-option [value]="'0'">Option 1</ng-option>
    <ng-option [value]="'1'">Option 2</ng-option>
    <ng-option [value]="'2'">Option 3</ng-option>
</ng-select>

component.ts

export class AppComponent  {
  dropdown = false;

  @ViewChild('father', {static: false}) father;
  @HostListener('document:click', ['$event'])
  public onClick(e) {
    const clickedInside = this.father.nativeElement.contains(e.target);
    if (!clickedInside) {
      this.dropdown = false;
    }else{
      this.dropdown=true;
    }
  }
}

have a look at https://github.com/ng-select/ng-select#inputs

I have altered your stackblitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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