我正在尝试将 Select 2 实现到我的 Angular 7 项目中。我遵循了从 github 实现的所有程序。但它仍然不起作用。当我向其中显示一些静态数据时,它会起作用。它不填充来自网络服务器的数据。请分享您的想法。下面是我的代码
HTML 代码:
<select2 [options]="areas" [settings]="{ width: '100%' }"></select2>
<div *ngFor="let ar of areas">
<p>{{ar.Area_Name}}</p>
</div>
组件代码:
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;
});
}
}
模型类:
export class ObjectAreas
{
AreaSno: number;
Area_Code: string;
Area_Name: string;
}
我在控制台中收到此错误:
TypeError: Cannot read property 'toString' of undefined
最佳答案
您需要为此使用 ng2-select2
库。
尝试按照此处演示的方式使用它。
https://github.com/NejcZdovc/ng2-select2
https://github.com/NejcZdovc/ng2-select2#prerequisites
同时将 areas
保留在数据属性中而不是选项中
<select2 [data]="areas" ></select2>
请参阅更新的 ngOnit 函数,它获取 res 对象并创建一个包含所有标题的数组。
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;
});
}
如果您想要一个用户 ID 数组,那么只需更改这一行
var x = res[i].title ;
到 var x = res[i].userId ;
关于angular - 我如何使 select2 与 Angular 7 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663382/