How do I make select2 to work with Angular 7

坚强是说给别人听的谎言 提交于 2019-11-30 17:59:35

问题


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 Code:

  <select2 [options]="areas" [settings]="{ width: '100%' }"></select2>

  <div *ngFor="let ar of areas">
    <p>{{ar.Area_Name}}</p>
  </div>

Component Code:

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;                           
        });              
  }

}

Model Class:

export class ObjectAreas
{
    AreaSno: number;
    Area_Code: string;
    Area_Name: string;
}

I get this error in console:

TypeError: Cannot read property 'toString' of undefined

回答1:


You will need to use ng2-select2 library for it.

Try using it the way it is demonstrated here.

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

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

Also keep the areas in data attribute instead of options

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

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;
        });      

  }

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



来源:https://stackoverflow.com/questions/54663382/how-do-i-make-select2-to-work-with-angular-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!