如何使select2与Angular 7一起使用

前端之家收集整理的这篇文章主要介绍了如何使select2与Angular 7一起使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的Angular 7项目中实现Select 2.我遵循了从 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

还要将区域保留在数据属性中而不是选项中

<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; to var x = res [i] .userId;

猜你在找的Angularjs相关文章