如何为Angluar 2 ng-select添加值和标签

时间:2018-10-03 09:17:02

标签: angular angular-ngselect

基本上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]的值设置为此值,则会得到元素的value属性的[object],[object]和一个空的下拉列表。 我怎样才能做到这一点?

更新
html:

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

2 个答案:

答案 0 :(得分:0)

尝试这样的事情

Project and External Dependencies

答案 1 :(得分:0)

如果您正在使用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);
  }