Angular 6 ng-select如何使用模板表达式设置在下拉列表中选择的项目

Md.*_*lah 2 angular-ngselect angular

在 Angular 6 项目中,我尝试使用ng-select节点包。在使用模板表达式时,我面临着在下拉列表中设置所选项目的困难。没有模板表达式,我可以设置在下拉列表中选择的项目。

我在 stackblitz 中创建了一个演示项目。请检查此处的代码https://stackblitz.com/edit/ngselect-demo

yur*_*zui 6

ng-select是关于比较数组中的元素的非常灵活的组件。

下面是负责比较的findItem函数:

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));
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它遵循以下规则:

1)compareWith如果提供了函数,则使用函数,否则

2)bindValue如果提供则使用,否则

3)bindLabel如果提供则使用

在您的第一个不使用您传递的模板表达式的控件中,bindLabel它可以正常工作。如果您将相同的输入添加到第二个控件,它将起作用

叉式堆栈闪电战

如果您想将选定的值保留为对象数组,那么我建议您使用compareWith输入

html

<ng-select 
  ...
  [compareWith]="compareWith"
Run Code Online (Sandbox Code Playgroud)

ts

compareWith(item, selected) {
  return item.id === selected.id
}
Run Code Online (Sandbox Code Playgroud)

堆栈闪电战示例

否则使用bindValue