Search code examples
angularangular-ngselect

How do I select an item in a ng-select list programmatically?


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


Solution

  • 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
    
    }