我如何使select2与Angular 7一起使用 [英] How do I make select2 to work with Angular 7

查看:120
本文介绍了我如何使select2与Angular 7一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的Angular 7项目中实现Select 2.我遵循了从github实现的所有过程.但仍然无法正常工作.当我向其中显示一些静态数据时,它可以工作.它不会填充来自Web服务器的数据.请分享您的想法.下面是我的代码

Am trying to implement Select 2 into my Angular 7 project. I followed all the procedures to implement from github. But still its not working. It works when i present some static data into it. Its not populating the data from the webserver. Please share your ideas. Below is my code

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库.

尝试以此处演示的方式使用它.

Try using it the way it is demonstrated here.

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

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

还要在数据属性中保留areas而不是选项

Also keep the areas in data attribute instead of options

<select2 [data]="areas" ></select2>

Seeu更新了ngOnit函数,该函数接受res对象并创建所有标题的数组.

Seeu updated ngOnit function, that takes the res object and creates an array of all titles.

  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 ;

In case you want an array of userids then just change this line var x = res[i].title ; to var x = res[i].userId ;

这篇关于我如何使select2与Angular 7一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆