How to get element reference of ng-select in angular

88 views Asked by At

I am trying to use enter key press event in angular and I am using ng-select for dropdown list but I am not able to get element reference of ng-select as it not native element of HTML ,I did use @ViewChildren and @ViewChild, but still I am not able get reference

 <ng-select class="form-control" #cityInput formControlName="city" [items]="cities"           (keydown)="onEnterKeyPress1($event)"> </ng-select>

this is my snippet in component.html, here I have given #cityInput reference and following is the code where I am trying to use this reference

@ViewChildren(
    ' cityInput ')  inputElement: QueryList<NgSelectComponent>;

how can i use focus method on ng-select

1

There are 1 answers

0
Naren Murali On

We need to use ViewChild to select a single element, we can use ViewChildren to select multiple children, we can either pass the reference or we can give the class directly as input and it will fetch the values after the view is loaded, so its important we access the values after the view has initialized ngAfterViewInit!

import {
  Component,
  ElementRef,
  QueryList,
  ViewChild,
  ViewChildren,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import { NgSelectModule, NgSelectComponent } from '@ng-select/ng-select';
import 'zone.js';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [NgSelectModule, FormsModule],
  template: `
    <ng-select class="form-control" #select [items]="cities"> </ng-select>
    <ng-select class="form-control"  [items]="cities"> </ng-select>
    <ng-select class="form-control" [items]="cities"> </ng-select>
    <ng-select class="form-control" [items]="cities"> </ng-select>
    <ng-select class="form-control" [items]="cities"> </ng-select>
  `,
})
export class App {
  // if you want to select multiple ng-select
  @ViewChildren(NgSelectComponent) inputElement!: QueryList<NgSelectComponent>;
  @ViewChildren('select') select!: QueryList<NgSelectComponent>;
  // if you want to select single ng-select
  @ViewChild(NgSelectComponent)
  inputElementSingle!: NgSelectComponent;
  @ViewChild('select') selectSingle!: NgSelectComponent;
  name = 'Angular';
  cities = [];

  ngAfterViewInit() {
    console.log('multiple');
    console.log(this.inputElement);
    console.log(this.select);
    console.log('single');
    console.log(this.inputElementSingle);
    console.log(this.selectSingle);
    // to select the focus , we can do.
    this.selectSingle.open();
  }
}

bootstrapApplication(App);

stackblitz