3

I'm using angular5 ng-select component: https://github.com/ng-select/ng-select and try to set the selected value (programatically) when the container component first loaded (kind of default selected value set in the model). I didn't find any relevant attribute for it or for the isSelected for each item. Here is my code (filtered): HTML:

<ng-select [items]="filter.values"  bindLabel="text" bindValue="id" class="input-md" [(ngModel)]="filter.selectedValue"></ng-select>

Model:

export class FilterData
{
    Name : string;
    FormattedName : string;
    values : Filter[];
    selectedValue : Filter = null;
    constructor(filterData : FilterData)
    {
        this.Name = filterData.Name;
        this.values = filterData.values;
        this.selectedValue = typeof filterData.selectedValue == "undefined" ? null : filterData.selectedValue;
    }
}

export class Filter 
{
    public id: number;
    public text: string;
}
VukDju
  • 63
  • 2
  • 12
Guy E
  • 1,775
  • 2
  • 27
  • 55

1 Answers1

10

Just find the item

    let item = this.ngSelect.itemsList.findByLabel('label of the item');

and then set it back

    this.ngSelect.select(item);

you need a reference to ng-select in your angular component

    @ViewChild(NgSelectComponent)
    ngSelect: NgSelectComponent;
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
  • ngselectcomponent is not defined – Jason G Oct 19 '18 at 21:44
  • Above code is working for me. But now it is giving me error of Expression has changed as i am using it with Reactive form. .changeDetection method of angular core is also not working. Any idea ? – Aakash Kumar Feb 28 '19 at 04:59