我正在使用ng-select组件(https://github.com/valor-software/ng2-select)。 我实现了一种在用户输入时远程获取数据的方法。 但是,将获取新数据并正确填充(项)对象,但视图不会刷新。
让我给你一些代码:
以下是模板:
<ng-select
#select
[allowClear]="'true'"
id="DropdownTypeaheadQuestion-{{ question.id }}"
[(items)]="items"
[formControl]="formControlToUse"
placeholder="{{ placeholderText }}"
[multiple]="isMultiple"
(selected)="execSelected($event)"
(typed)="execKeypress($event)">
</ng-select>
控制器:此方法在按键上执行:
execKeypress($event) {
// When remote, clear all items directly on keypress. Else we have an ugly lag because of the debounce time.
if (this.config.remote === true) {
this.items = [];
}
this.searchSubject.next($event);
}
控制器:在ngInit上我订阅了该事件以获取新数据:
// Inside ngOnInit I subscribe to the observable
this.searchSubject.debounceTime(500)
.takeUntil(this.ngUnsubscribe)
.subscribe( (searchTextValue: string) => {
// save search string on scope
this.searchTextValue = searchTextValue;
this.config.httpParams = this.config.httpParams.set('search', searchTextValue);
// only send search if more than x chars (or empty)
if (searchTextValue === '' || searchTextValue.length >= this.config.minChars) {
this.fetchResults();
}
});
控制器:这是获取结果的方法:
// fetchResult method fetches the new items and appends them to the items array
this.httpClient.get(url, {params: this.config.httpParams})
.takeUntil(this.ngUnsubscribe)
.subscribe( (res: any) => {
this.items = this.transformSelectableValuesToConsumables(res);
this.select.items = this.items;
this.loadingResults = false;
},
(error) => {
this.loadingResults = false;
// TODO: Implement proper error handling
});
对象的一切正常工作:items数组被填充并正确填充。但是,只有当我关注并重新进入时,下拉才会关闭并打开。似乎是组件中的错误。我还在他们的github上提出了一个问题:
https://github.com/valor-software/ng2-select/issues/929
非常感谢任何帮助:)
答案 0 :(得分:1)
现在我找到了解决方案。
在回调中,您需要分配新项目,手动打开下拉列表:
// fetchResult method fetches the new items and appends them to the items array
this.httpClient.get(url, {params: this.config.httpParams})
.takeUntil(this.ngUnsubscribe)
.subscribe( (res: any) => {
this.items = this.transformSelectableValuesToConsumables(res);
this.select.items = this.items;
// [BUGFIX] Here we open the select manually
(<any>this.select).open();
this.loadingResults = false;
},
(error) => {
this.loadingResults = false;
// TODO: Implement proper error handling
});
并删除组件模板中的[items]分配:
<ng-select
#select
[allowClear]="'true'"
id="DropdownTypeaheadQuestion-{{ question.id }}"
[formControl]="formControlToUse"
placeholder="{{ placeholderText }}"
[multiple]="isMultiple"
(selected)="execSelected($event)"
(typed)="execKeypress($event)">
</ng-select>
因此,这些项目将完全通过控制器中的@ViewChild
分配进行处理。
以下是整个解决方案: https://github.com/valor-software/ng2-select/issues/635#issuecomment-281094377