我正在开发angular2应用程序,我已经使用ng2-select进行多选下拉列表。它在创建新条目时工作正常。但是当在编辑时尝试实现相同功能时,我无法设置从数据库中提取的默认选定值。
<ng-select [initData]="aminities" (data)="refreshValue($event)" [multiple]="true" [items]="items" [disabled]="disabled"></ng-select>
export class EditProjectComponent {
project: ProjectModel;
routeParam: RouteParams;
aminities: any;
private items: Array<string> = ['Swimming Pool', 'Gymnasium', 'Lift', 'Power Backup',
'Landscaped Garden', 'Security', 'Community Hall', 'Jogging Track', 'Childrens Play Area'];
constructor(
@Inject(Router) private router: Router,
@Inject(ProjectService) private projectService: ProjectService,
routeParam: RouteParams,
private _formBuilder: FormBuilder
) {
this.project = new ProjectModel();
this.routeParam = routeParam;
if (this.routeParam.params['id'] != undefined) {
this.projectService.getbyId(this.routeParam.params['id'], (res) => {
this.project = res;
this.aminities = this.project.overview.aminities;
}, () => { });
}
}
}
在回复之后,我必须在ng2-select中设置 aminities 值。
请更正我如何设置默认选定值。
答案 0 :(得分:4)
如果您想从响应中返回后选择所有aminities
,则可以通过将其推送到active
来触发它。
这是我发现的唯一方法。肯定有更好的选择。
首先我们将select添加为视图子项。
import {Select} from 'your-location';
export class EditProjectComponent {
//...
@ViewChild(Select)
private select: Select;
//...
}
(如果您有超过1,请使用@viewChildren
和QueryList<>
)
之后,我们首先找到从itemObjects
。
let arr = [];
arr = this.select.itemObjects.filter((x) => {
let isAminities = this.aminities.find((y) => y.text === x.text);
return (isAminities !== -1) ? true: false;
})
现在我们已经arr
包含了我们需要的所有项目,我们只需将其推送到选择的有效列表。
this.select.active.push(arr)
最终结果:
export class EditProjectComponent {
project: ProjectModel;
routeParam: RouteParams;
aminities: any;
@ViewChild(Select)
private select: Select;
private items: Array<string> = ['Swimming Pool', 'Gymnasium', 'Lift', 'Power Backup',
'Landscaped Garden', 'Security', 'Community Hall', 'Jogging Track', 'Childrens Play Area'];
constructor(
@Inject(Router) private router: Router,
@Inject(ProjectService) private projectService: ProjectService,
routeParam: RouteParams,
private _formBuilder: FormBuilder
) {
this.project = new ProjectModel();
this.routeParam = routeParam;
if (this.routeParam.params['id'] != undefined) {
this.projectService.getbyId(this.routeParam.params['id'], (res) => {
this.project = res;
this.aminities = this.project.overview.aminities;
let arr = [];
arr = this.select.itemObjects.filter((x) => {
let isAminities = this.aminities.find((y) => y === x.text);
return (isAminities !== -1) ? true: false;
})
this.select.active.push(arr)
}, () => { });
}
}
}
我知道还有其他选择可以做到这一点。但到目前为止,这是我能够合作的唯一一个。