问题
Am trying to implement Select 2 into my Angular 7 project. I followed all the procedures to implement from github. But still its not working. It works when i present some static data into it. Its not populating the data from the webserver. Please share your ideas. Below is my code
Html Code:
<select2 [options]="areas" [settings]="{ width: '100%' }"></select2>
<div *ngFor="let ar of areas">
<p>{{ar.Area_Name}}</p>
</div>
Component Code:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ObjectAreas } from './areasObject';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [
'./app.component.css',
'../../node_modules/bootstrap/dist/css/bootstrap.min.css'
]
})
export class AppComponent
{
apiURL: string = 'http://localhost/support/php/getAreas.php?areasno=0';
constructor(private httpClient: HttpClient) { }
areas: ObjectAreas;
public getContacts()
{
return this.httpClient.get(this.apiURL);
}
ngOnInit()
{
this.getContacts()
.subscribe((res:ObjectLoan)=>
{
this.areas = res;
});
}
}
Model Class:
export class ObjectAreas
{
AreaSno: number;
Area_Code: string;
Area_Name: string;
}
I get this error in console:
TypeError: Cannot read property 'toString' of undefined
回答1:
You will need to use ng2-select2
library for it.
Try using it the way it is demonstrated here.
https://github.com/NejcZdovc/ng2-select2
https://github.com/NejcZdovc/ng2-select2#prerequisites
Also keep the areas
in data attribute instead of options
<select2 [data]="areas" ></select2>
Seeu updated ngOnit function, that takes the res object and creates an array of all titles.
ngOnInit()
{
this.getContacts()
.subscribe((res:any)=>
{
console.log(res)
var arr = [];
for(var i=0; i<res.length; i++) {
var x = res[i].title ;
arr.push(x);
}
//console.log(arr)
this.users = arr;
});
}
In case you want an array of userids then just change this line
var x = res[i].title ;
to var x = res[i].userId ;
来源:https://stackoverflow.com/questions/54663382/how-do-i-make-select2-to-work-with-angular-7