以编程方式在angular5 ng-select中设置选择的值

以编程方式在angular5 ng-select中设置选择的值

问题描述:

我正在使用angular5 ng-select组件: > https://github.com/ng-select/ng-select 并尝试在首次加载容器组件时设置(以编程方式)选定值(模型中设置的默认选定值的种类). 我没有找到任何相关属性或每个项目的 isSelected . 这是我的代码(已过滤): HTML:

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>

型号:

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

只需找到该项目

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

然后将其重新设置

    this.ngSelect.select(item);

您需要在角度分量中引用ng-select

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

    @ViewChild(NgSelectComponent)
    ngSelect: NgSelectComponent;