角度下拉列表不显示文本

时间:2018-12-26 18:50:51

标签: angular typescript components

我正在尝试在KeyValue角度分量中显示p-dropdown个项目的数组。它正在拾取正确数量的数据(5),但在下拉列表中未显示任何文本?

enter image description here

键值.ts

export interface KeyValue {
    label: string;
    value: string;
}

dd.json

{ 
  "Domains": [
    {"label": "North America (NAM)", "value": "NAM"}, 
    {"label": "Europe (EUR)", "value": "EUR"}, 
    {"label": "Australia (AUS)", "value": "AUS"}, 
    {"label": "Latin America (LAAM)", "vaule": "LAAM"}, 
    {"label": "Asia (APA)", "value": "APA"}
  ]
}

component.html

<div class="container">
  <div>Domain:<span class="required">*</span></div>
  <p-dropdown [options]="domains" formControlName="domain" optionLabel="text" (onChange)="dataChanged($event, 'domain')" placeholder="Select an option"></p-dropdown>
  <br>
</div>

component.ts

import { KeyValue } from '../../model/key-value';

export class RequestComponent implements OnInit {
  domains:  KeyValue[] = [];

  constructor(private service: Service) {}

  ngOnInit() {
    this.getPageData();
  }

  getPageData() {
    console.log("getPageData() First: " + this.domains);
    this.service.getDomains().subscribe(domains => {console.log("getPageData() Second: " + domains); this.domains = domains});
    console.log("getPageData() Third: " + this.domains);
  }
}

service.ts

@Injectable()
export class Service{

  constructor(private http: HttpClient) { }

  getDomains(): Observable<any> {
    return this.getJSON()
      .pipe(
        map(
          data => { data.Domains;
                    console.log("getDomains(): " + data.Domains); } ));}

  getJSON(): Observable<any> {
    return this.http.get("assets/dd.json");
  }
}

控制台消息

getPageData() First: 
getPageData() Third: 
getDomains(): [object Object],[object Object],[object Object],[object Object],[object Object]
getPageData() Second: undefined

编辑

我对getDomains()方法进行了更新,并增加了额外的回报:

getDomains(): Observable<any> {
  return this.getUNPProperties().pipe(map(data => { console.log("getDomains(): " + data.Domains); return data.Domains}));
}

控制台消息如下:

getPageData() First: 
getPageData() Third: 
getDomains(): [object Object],[object Object],[object Object],[object Object],[object Object]
getPageData() Second: [object Object],[object Object],[object Object],[object Object],[object Object]

1 个答案:

答案 0 :(得分:2)

请将optionLabel属性设置为'label'。默认情况下, PrimeNg 下拉列表将label作为显示字段,将value作为值字段。通过将optionLabel更改为'text'将查找名称为text且在domains列表中不可用的字段。

因此,p-dropdown的更新代码如下。

<p-dropdown 
   [options]="domains" 
   formControlName="domain" 
   optionLabel="label" 
   (onChange)="dataChanged($event, 'domain')" 
   placeholder="Select an option">
</p-dropdown>