如何让select2与Angular 7一起使用

4
我正在尝试将Select 2实现到我的Angular 7项目中。我按照从Github实现的所有过程进行了操作。但是它仍然没有工作。当我向其提供一些静态数据时,它可以正常工作。但是它无法从Web服务器填充数据。请分享您的想法。以下是我的代码:
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

相反,ObjectLoan 使用 ObjectAreas,它应该使用数组来遍历。 - TheParam
将其创建为类似于ObjectAreas []的数组,并确保从Web服务获取对象数组。 - TheParam
我将它变成了数组,但是没有得到结果。我从 Web 服务中获取了对象。我已经在 HTML 中将它们显示出来了。 - Srinivasan Ra
是的,我已经转换成了数组。但是列表没有填充。 - Srinivasan Ra
但是当我像这样提供一些静态数据时,它可以工作:this.areas = ['A1', 'B2', 'C3', 'D4', 'E5']; - Srinivasan Ra
显示剩余2条评论
2个回答

1

您需要使用ng2-select2库。

尝试按照这里演示的方式使用它。

https://github.com/NejcZdovc/ng2-select2

https://github.com/NejcZdovc/ng2-select2#prerequisites

同样,将areas保留在数据属性中而不是选项中。
<select2 [data]="areas" ></select2>

Seeu更新了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 ;

我改成了 this.areas = [res]; //转换为数组... 但在HTML中,我只得到了[object Object, object Object]而不是值... - Srinivasan Ra
请问您能否在Stackblitz或Plunker上复制它,并添加链接以检查问题所在。我认为这不是正确的做法:this.areas = [res]; - Nandita Sharma
请问您能告诉我您的 res 对象的结构吗? - Nandita Sharma
1
请查看更新的tsackblitz。https://stackblitz.com/edit/angular-k1ejax?file=src/app/app.component.ts - Nandita Sharma
1
我会查看并告诉您是否发现了什么。 - Nandita Sharma
显示剩余9条评论

0

它接受特定格式的数据,例如

[
    {
        id: 'uniqe_id',
        text: 'text_to_display'
    }
]

你必须先将你的数据转换为这种格式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接