I have several ng-selects on a page, and am trying to open one from ts.
I am able to focus on the right ng-select using the following:
@ViewChildren(NgSelectComponent) ngselect: QueryList<NgSelectComponent>;
this.ngselect.last.filterInput.nativeElement.focus()
However, I'm not able to open. I tried the below
this.ngselect.last.filterInput.nativeElement.open()
but get the error:
_this.ngselect.last.filterInput.nativeElement.open is not a function
.open() is a method though...how can I get this to work? https://github.com/ng-select/ng-select#methods
Have You tried something like this
<ng-select #Selecter ></ng-select>
@ViewChild('Selecter') ngselect: NgSelectComponent;
ngAfterViewInit() {
this.ngselect.open();
}
Working Example Links To stackblitz
There's a far easier way to achieve what you want. If you check the documentation (found here: https://github.com/ng-select/ng-select#api), you'll find you can pass isOpen
to ng-select
. Changes to the value of isOpen
passed to the right ng-select
would open and close it automatically.
Example:
<ng-select
[isOpen]="isOpen"
[items]="items"
>
</ng-select>
and in the component class, you can simply change isOpen and that would open and close the select.
You may also need to open it in your test file, for when you want to check items in the DOM, etc:
1. Create a file and add this (or add to an existing file if you prefer)
import { DebugElement } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
/*
* Utils based on ng-select helper functions:
https://github.com/ng-select/ng-select/blob/3018a1098ba2ad06fbdf4dfe60209087cbd68185/src/ng-select/testing/helpers.ts
*/
export function getNgSelectElement(fixture: ComponentFixture<any>): DebugElement {
return fixture.debugElement.query(By.css('ng-select'));
}
export function triggerKeyDownEvent(element: DebugElement, which: number, key = ''): void {
element.triggerEventHandler('keydown', {
which: which,
key: key,
preventDefault: () => { },
});
}
2. Import the functions into your test file and use them like this:
// Open the dropdown
triggerKeyDownEvent(getNgSelectElement(fixture), 32);
fixture.detectChanges();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With