简体   繁体   中英

Angular2 toggle/open ng2-select dropdown

Angular 4.3+

I am using ng2-select dropdown.

I want the drop down to be opened on some event. I want to trigger the event that would open the drop down.

Dropdown:

<ng-select
        [items]="list"
        [(ngModel)]="modelName"
        placeholder="Select">
</ng-select>

When the user clicks on the dropdown it gets focus and the list is being displayed. I would like this happen on some click event on the different button.

What I have tried so far:

this.el is ElementRef to the ng-select element. (Getting the element reference for ng-select correctly, it console log correct element that I am trying to trigger events.)

  1. As it opens when the user clicks on it, I tried to trigger a click event on an element. this.el.nativeElement.click();
  2. Tried to trigger click event on .ui-select-toggle element. this.el.nativeElement.querySelector('.ui-select-toggle').dispatchEvent(new Event('click'));
  3. Similarly I tried to trigger focus event but didn't work.

Is there any other way that we can trigger some event on ng-select element that gets focus on ng-select and get the drop down open.

I wrap up the click event trigger code inside the setTimeOut function like below and it is working fine now.

setTimeout(() => {
     this.el
         .nativeElement
         .querySelector('.ui-select-toggle')
         .dispatchEvent(new Event('click'));
});

.ui-select-toggle is the element does dropdown toggle on click, so I figured if I trigger click event on that element it will toggle/open the drop-down.

So I tried the following(without the setTimeOut wrapper)

this.el
         .nativeElement
         .querySelector('.ui-select-toggle')
         .dispatchEvent(new Event('click'));

And it did nothing. But when I wrap that code in setTimeOut it actually triggers the click event and I get expected functionality.

Here I am not sure why it functions like that but I believe this is something related to javascript.

If you are using multiple mode:

openNg2Select(ng2Select: SelectComponent) {
    setTimeout(() => {
        const ng2 = ng2Select.element.nativeElement.querySelector('.ui-select-search');
        ng2.dispatchEvent(new Event('click'));
    });
}

In HTML:

<ng-select #ng2Select [multiple]="true" [items]="items" (selected)="selected($event)"
           (removed)="removed($event)" placeholder="Please Select" 
           [(ngModel)]="selectedItem">
</ng-select>
<button class="btn btn-pripary" (click)="openNg2Select(ng2Select)>Open ng2-select</button>

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