Search code examples
angularangular-ngselect

angular 6 ng-select how to set item selected in drop down list by using template expression


In Angular 6 project, I am trying to use ng-select node package. I am facing the difficulty to set item selected in dropdown list while using template expression. Without template expression, I am able to set item selected in dropdown list.

I have created a demo project in stackblitz. Pls check the code here https://stackblitz.com/edit/ngselect-demo


Solution

  • ng-select is very flexible component regarding comparing elements in an array.

    Here is the findItem function which is responsible for this comparison:

    findItem(value: any): NgOption {
        let findBy: (item: NgOption) => boolean;
        if (this._ngSelect.compareWith) {
            findBy = item => this._ngSelect.compareWith(item.value, value)
        } else if (this._ngSelect.bindValue) {
            findBy = item => !item.children && this.resolveNested(item.value, this._ngSelect.bindValue) === value
        } else {
            findBy = item => item.value === value ||
                !item.children && item.label && item.label === this.resolveNested(value, this._ngSelect.bindLabel)
        }
        return this._items.find(item => findBy(item));
    }
    

    As you can see it follows the following rules:

    1) Use compareWith function if provided, else

    2) Use bindValue if provided, else

    3) Use bindLabel if provided

    In your first control that doesn't use template expression you passed bindLabel thus it works properly. If you add the same input to your second control it will works

    Forked Stackblitz

    If you want to keep selected value as array of objects then I would recommend you using compareWith input

    html

    <ng-select 
      ...
      [compareWith]="compareWith"
    

    ts

    compareWith(item, selected) {
      return item.id === selected.id
    }
    

    Stackblitz Example

    otherwise use bindValue