问题
I have many drop-downs in my angular2js project. I am using ng2-select2 for these drop-down. In some dropdown, I need to filter and fetch data from an API as per the string user types into the select2 search box. The plug-in initializes but doesn't fire any AJAX.
My code so far:
HTML:
<select2 [data]="options | async"></select2>
Component:
import { Component,OnInit } from '@angular/core';
import {Select2OptionData} from 'ng2-select2';
import {AlertService, LTJService} from '../../_services/index';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'nationalities',
templateUrl: '../../views/buyer_profile/nationalities.component.html',
})
export class NationalityComponent implements OnInit {
//public nationalities: Observable<Array<Select2OptionData>>;
public options: Select2Options;
public ajaxOptions: Select2AjaxOptions;
constructor(private alertService: AlertService, private ltjService: LTJService) {
}
ngOnInit(): void {
console.log('In ngOnInit');
this.ajaxOptions = {
url: '<API URL>',
dataType: 'json',
delay: 250,
cache: false,
data: (params: any) => {
console.log("AA", params);
return {
query: params.term,
gotoPage: params.page
}
},
processResults: (data: any, params: any) => {
params.page = params.page || 1;
console.log('data: ', data);
return {
results: $.map(data.data, function(obj) {
return {id: obj.id, text: obj.name};
}),
pagination: {
more: (params.page * 10) < data.objectValue.total_count
}
};
},
};
this.options = {
ajax: this.ajaxOptions
}
}
}
Can anyone point me into the right direction? Any help is really appreciated.
回答1:
you use [data] which will input only data not option
<select2 [data]="options | async"></select2>
try
<select2 [options]="options | async"></select2>
来源:https://stackoverflow.com/questions/46050414/use-ajax-in-ng2-select2