如何使Select2与Angular 7一起使用



正在尝试将选择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

您需要使用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 ;

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

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

您必须先以这种格式转换数据。

最新更新