如何使select2与Angular 7一起使用
发布时间:2020-12-17 17:12:11 所属栏目:安全 来源:网络整理
导读:我试图在我的Angular 7项目中实现Select 2.我遵循了从 github实现的所有过程.但它仍然不起作用.当我向其中呈现一些静态数据时,它可以工作.它没有填充来自网络服务器的数据.请分享您的想法.以下是我的代码 Html代码: select2 [options]="areas" [settings]="
我试图在我的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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |