1

My application shows the user a list that uses ng-select. This list contains several items

  • item 1
  • item 2
  • item N

The user can do one of two things with the previous list. He can choose an existing item, or he can add a new item. If the user adds a new item to the list, the new item needs to be automatically added to the list and selected.

I've already managed to implement the add-to-list functionality. However, I haven't found a way to implement the functionality to programmatically select an item in the list.

Is there a way of doing so with ng-select? Thanks in advance

edoreld
  • 303
  • 1
  • 17
  • You most definitely have to have some kind of value binding, take a look at `ngModel` or `ReactiveForms` – Dmitriy Nov 23 '20 at 16:14

1 Answers1

2

Use [(ngModel)] associated with a typescript variable.

<ng-select[(ngModel)]="selectedItem">
    ....
</ng-select>

Programmatically set the variable = your last added item.

selectedItem:any;

functionAddItemToList(){
.....
this.selectedItem = NewItem_Just_Added

}
Tiago Silva
  • 223
  • 2
  • 6
  • I tried to use [(ngModel)] and it works, but I get a warning that using ngModal along form controls is deprecated and shouldn't be used. – edoreld Nov 24 '20 at 16:07
  • 1
    I didnt know you were using form control. I normally dont use them. Here you have some options for this waning. https://stackoverflow.com/questions/49918503/angular-6-warning-for-using-formcontrolname-and-ngmodel – Tiago Silva Nov 24 '20 at 20:40