如何为ng2-select设置默认值

时间:2016-05-22 23:11:05

标签: angular ng2-bootstrap

  

data(?Array) - 要设置的初始选择数据。在输入类型为“Single”的情况下,这应该是具有id和text属性的对象,否则应该是具有此类对象的数组。此选项与值互斥。

这是来自网站文档。 GitHub调用initData引发错误。

我使用一系列有效选项设置[data],但未选择任何内容。此外,每次打开下拉列表时,我都会看到这一点。

这在单一模式下也不起作用。

如何为此控件预先选择“选项”?

我在RC.1中使用它。 SO上的其他解决方案看起来像旧版本的ng2。

4 个答案:

答案 0 :(得分:2)

多重标签下的

https://valor-software.com/ng2-select/显示了[data]元素的使用。根据项目自述文件,这是不正确的。

用[initData]替换[data],如果数据格式正确,则预填充工作。

答案 1 :(得分:1)

你应该使用

<ng-select [active]="[periods[0]]" [data]="periods"></ng-select>

enter image description here

答案 2 :(得分:1)

这对我有用:

<ng-select #my-select [multiple]="true" [items]="dataList"></ng-select>

导入以下类:

import { ViewChild } from '@angular/core';
import { SelectComponent, SelectItem } from 'ng2-select';

在组件类中,使用my-select装饰器访问@ViewChild组件:

@ViewChild('my-select') mySelectComponent: SelectComponent;

深入了解ng2-select源代码,提示active上的SelectComponent属性包含所选值。此外,activeSelectItem个对象的数组。因此,创建SelectItem个对象并将其推入active数组应允许您以编程方式添加/删除所选项目。

回到你的问题,我们为ng2-select设置几个默认值:

ngOnInit() {
    if(!this.mySelectComponent.active) {
        this.mySelectComponent.active = new Array<SelectItem>();
    }
    this.mySelectComponent.active.push(new SelectItem("Apple"));
    this.mySelectComponent.active.push(new SelectItem("Banana"));
}

您还可以清除所有现有值:

reset() {
    if(this.mySelectComponent.active) {
        this.mySelectComponent.active.length = 0;
    }
}

注意:SelectItem构造函数将字符串或对象作为参数。如果传入字符串,则idtext将设置为字符串值。如果您想为idtext传递不同的值,可以执行以下操作:

this.mySelectComponent.active.push(new SelectItem({id:'apl', text:'Apple'}));

答案 3 :(得分:0)

当前版本的文档更好地解释了:ng2-select / valor-software.com

查看方( category-edit.component.html ):

<ng-select [multiple]="true" [items]="tags" [active]="active_tags"></ng-select>

无论是否有一个或多个元素,始终必须包含数组格式,例如:[{id:1,text:MyText}]或[{id:1,text:MyText1},{id :2,文字:MyText2}]

组件方( category-edit.component.ts ):

import {Component, OnInit, Injectable} from '@angular/core';

@Injectable()
export class MyService {

   getTagsByCategoryId(id: string): Observable<any> { /** callback */}
}

export interface SelectOption{
   id?: string;
   text?: string;
}

@Component({
  selector: 'app-category-edit',
  templateUrl: 'category-edit.component.html'     
});

export class CategoriesComponent extends OnInit{
   tags: SelectOption[]; /** Assumed you already loaded these */ 
   active_tags: SelectOption[];     

 constructor(private myService:MyService){
   super();
 }
 ngOnInit(){
   this.init();
 }

 init(){

   const id= "the_id"; /** Some valid id to query */
   /** Callback */
   this.myService
       .getTagsByCategoryId(id)(
          response=> {
            if(response.error){ console.error(response.error);}   
            }else{
               console.log(response.result;)
               this.active_tags= <SelectOption[]> response.result;
            }  
          },
          error => {console.error(error);}
     );
 }

}

相关问题