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