set selected value in angular5 ng-select programmaticaly

心已入冬 提交于 2020-01-11 12:15:10

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/49168270/set-selected-value-in-angular5-ng-select-programmaticaly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!