← All posts

Ng-Select: How to add items programmatically | Angular

It would seem such a simple task, but not everything is as easy as it seems at first time. If you think that it is necessary to push into the array with values and that’s all, then you are wrong. I’ll show you why below.
First of all, install the ng-select package:

npm install --save @ng-select/ng-select

Be careful with versions:

Import the NgSelectModule and angular FormsModule modules:

// app.module.ts
import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [AppComponent],
imports: [NgSelectModule, FormsModule],
bootstrap: [AppComponent]
})
export class AppModule {}

Include a theme:

@import "~@ng-select/ng-select/themes/default.theme.css";
// ... or
@import "~@ng-select/ng-select/themes/material.theme.css";

Prepare the code:

// app.component.ts
@Component({...})
export class ExampleComponent {

selectedCar: number;

cars = [
{ id: 1, name: 'Volvo' },
{ id: 2, name: 'Saab' },
{ id: 3, name: 'Opel' },
{ id: 4, name: 'Audi' },
];
}
// app.component.html
<ng-select [items]="cars" 
bindLabel="name"
bindValue="id"
[multiple]="true"
[(ngModel)]="selectedCar">
</ng-select>

Now you are ready for the most interesting things. If you do the next step it doesn’t work:

this.cars.push({ id: 5, name: 'BMW' });
this.selectedCar.push(5);

First of all, you need to use ‘ViewChild’ directive:

// app.component.ts
@ViewChild('myselect') myselect: any;
// app.component.html
<ng-select #myselect
[items]="cars"
bindLabel="name"
bindValue="id"
[multiple]="true"
[(ngModel)]="selectedCar">
</ng-select>

Then, you have to use native ng-select methods, like this:

public addItems(){
let oneCar = { id: 5, name: 'BMW' };
this.myselect.itemsList.addItem(oneCar);
const item = this.myselect.itemsList.findByLabel('BMW');
this.myselect.select(item);
}

You can find a full list of ng-select methods in the documentation (and this).
I hope that I helped you in solving your problem.