如何将值和标签添加到 Angular 2 ng-select

How to add value and label to Angular 2 ng-select

基本上 ng2-select 模块允许我向其项目添加一维数组:

items = ['option 1', 'option 2', 'option 3'];

看起来像: ng-select dropdown

但我想要的是设置此类项目:

items = [
  { value: '1', label: 'Option 1' },
  { value: '2', label: 'Option 2' },
  { value: '3', label: 'Option 3' },
];

如果我将 [items] 的值设置为此值,我会在元素的值属性上得到 [object],[object] 和一个空的下拉列表。 我怎样才能做到这一点?

更新

<ng-select
  [items]="items" 
  bindLabel="nested.label"
  bindValue="nested.value">
</ng-select>

项目:

items = [
  { id: 1, nested: { value: '1', label: 'Option 1' } },
  { id: 2, nested: { value: '2', label: 'Option 2' } },
  { id: 3, nested: { value: '3', label: 'Option 3' } },
];

渲染 HTML:

<ng-select _ngcontent-c2="" bindlabel="nested.label" bindvalue="nested.value" _nghost-c5="" ng-reflect-items="[object Object],[object Object">
  <!--bindings={ "ng-reflect-ng-if": "true" }-->
  <div _ngcontent-c5="" class="ui-select-container dropdown open" tabindex="0" ng-reflect-off-click-handler="function () { [native code] }"> <div _ngcontent-c5="" ng-reflect-ng-class="[object Object]">
    </div>
    <!--bindings={ "ng-reflect-ng-if": "true" }-->
    <div _ngcontent-c5="" class="ui-select-match">
      <span _ngcontent-c5="" class="btn btn-default btn-secondary form-control ui-select-toggle" style="outline: 0;" tabindex="-1">
        <!--bindings={ "ng-reflect-ng-if": "true" }-->
        <span _ngcontent-c5="" class="ui-select-placeholder text-muted"></span> <!--bindings={ "ng-reflect-ng-if": "false" }-->
        <i _ngcontent-c5="" class="dropdown-toggle pull-right"></i>
        <i _ngcontent-c5="" class="caret pull-right"></i>
        <!--bindings={ "ng-reflect-ng-if": "false" }-->
      </span>
    </div>
    <!--bindings={ "ng-reflect-ng-if": "false" }-->
    <!--bindings={ "ng-reflect-ng-if": "false" }-->
    <!--bindings={ "ng-reflect-ng-if": "false" }-->
  </div> <!--bindings={ "ng-reflect-ng-if": "false" }-->
</ng-select>

尝试这样的事情

 <select>
  <option *ngFor="let item of items" [value]="item.value">
    {{item.label}}
  </option>
</select>

如果您使用的是 ng2-select 模块,请执行此操作。

模板

  <ng-select 
             [items]="items"             
             (selected)="selected($event)"></ng-select>

ts

   items = [
            { id: '1', text: 'Option 1' },
            { id: '2', text: 'Option 2' },
            { id: '3', text: 'Option 3' },
        ];


  public selected(value:any):void {
    console.log('Selected value is: ', value);
  }