i'm trying to use focus for ng-select in angular 5 but its not working
i'm working with ng2-select
How to use focus for ng-select in Angular 5 ?
<label class="input">
<input (blur)="goTo()" type="text">
</label>
<label class="select" >
<div *ngIf="items.length > 0" >
<ng-select #select [items]="items">
</ng-select>
</div>
</label>
@ViewChild('select') myElement: ElementRef;
goTo(){
this.myElement.element.nativeElement.focus();
}
Change this
goTo(){
this.myElement.element.nativeElement.focus();
}
to this,
import { ChangeDetectorRef } from '@angular/core';
constructor (private cRef: ChangeDetectorRef) {}
// import 'SelectComponent' from your library for 'ng2-select'
goTo(){
let el = null;
if (this.items.length > 0) {
this.cRef.detectChanges();
el = (this.myElement.nativeElement as SelectComponent).element.nativeElement.querySelector('div.ui-select-container > input');
if (el) { el.focus(); }
}
}
You may have to check if the element is defined or not (or if you need an extra 'nativeElement' in there, but I'm basically reusing the logic in here.
Just a cautionary note, this may not be a stable fix though if the library updates to rename these classes or modify the template.
Hope it helps.