data(?Array) - 要设置的初始选择数据。在输入类型为“Single”的情况下,这应该是具有 id 和 text 属性的对象,否则应该是此类对象的数组。此选项与值互斥。
这是来自网站文档。GitHub 调用 initData 会引发错误。
我正在使用一组有效选项设置 [data],但没有选择任何内容。此外,每次打开下拉菜单时,我都会看到它甚至会触发。
这也不适用于单一模式。
如何为该控件预先选择“选项”?
我将它与 RC.1 一起使用。SO 上的其他解决方案看起来像旧版本的 ng2。
data(?Array) - 要设置的初始选择数据。在输入类型为“Single”的情况下,这应该是具有 id 和 text 属性的对象,否则应该是此类对象的数组。此选项与值互斥。
这是来自网站文档。GitHub 调用 initData 会引发错误。
我正在使用一组有效选项设置 [data],但没有选择任何内容。此外,每次打开下拉菜单时,我都会看到它甚至会触发。
这也不适用于单一模式。
如何为该控件预先选择“选项”?
我将它与 RC.1 一起使用。SO 上的其他解决方案看起来像旧版本的 ng2。
https://valor-software.com/ng2-select/在多个选项卡下显示了 [data] 元素的使用。根据项目自述文件,这是不正确的。
将 [data] 替换为 [initData],如果数据格式正确,预填充将起作用。
这对我有用:
<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保存了选定的值。此外,active是一个SelectItem对象数组。因此,创建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构造函数将字符串或对象作为参数。如果你传入一个字符串,idandtext将被设置为字符串值。如果你想为idand传递不同的值text,你可以这样做:
this.mySelectComponent.active.push(new SelectItem({id:'apl', text:'Apple'}));
当前版本的文档解释得更好: ng2-select / valor-software.com
查看端(category-edit.component.html):
<ng-select [multiple]="true" [items]="tags" [active]="active_tags"></ng-select>
无论是一个还是多个元素,都必须包含数组格式,例如:[{id: 1, text: MyText}] or [{id: 1, text: MyText1}, {id: 2, text: 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);}
);
}
}