Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus for ng-select not working Angular 5

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();
    }
like image 972
LMA Avatar asked Aug 30 '25 18:08

LMA


2 Answers

this works fine for me,

@ViewChild('ngSelect') ngSelect: NgSelectComponent;
ngAfterViewInit() {
        if (this.autofocus) {
            setTimeout(() => {
                this.ngSelect.focus();
            });
        }
    }

refer https://github.com/ng-select/ng-select/issues/762

like image 157
Ali Avatar answered Sep 02 '25 06:09

Ali


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.

like image 40
amal Avatar answered Sep 02 '25 08:09

amal