【问题标题】:How do I make select2 to work with Angular 7如何使 select2 与 Angular 7 一起使用
【发布时间】:2019-07-06 21:14:16
【问题描述】:

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

【问题讨论】:

  • 相反,ObjectLoan 使用 ObjectAreas,它应该数组遍历
  • 我只使用 ObjectAreas。我在这里输入错误..
  • 使其像 ObjectAreas[] 一样排列,并确保从 Web 服务中获取对象数组
  • 我把它做成了数组。但没有得到。我正在从 Web 服务获取对象。我在下面的 html 中显示了它们 ..
  • 所以除非你从服务中获取数组,否则它不会工作

标签: angular jquery-select2 angular7


【解决方案1】:

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

【讨论】:

  • 我改成this.areas = [res]; //转换成数组..但是在html中我只得到[object Object, object Object]而不是值...
  • 能否请您在 stackblitz 或 plunker 上复制它并添加链接以检查问题出在哪里。我不认为 this.areas = [res];是正确的做法
  • 你能说说你的 res 对象的结构吗?
  • 会调查一下,如果我发现了什么,会通知你
【解决方案2】:

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

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

你必须先把你的数据转换成这种格式。

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 2015-12-13
    • 2018-04-22
    • 2016-11-23
    • 2021-03-12
    • 2014-07-12
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多