简体   繁体   中英

Populate the data in drop-down from a GET json response- Angular4

I am trying to show json keys/fields in a dropdown for commands; which is Object type(see json below) Eg: "key1","key2" should appear in dropdown. Initially used *ngfor but it gives error- "ngfor only supports binding for iterables such as Arrays". Since my json doesn't contain Array, so tried using ng-options in but not able to populate the dropdown. My json looks like:

{
    id: ‘bla’,
    commands: {
        “key1” : { },
        “key2”: { }
    }
}

html code:

<select ngModel="selectedName" ng-options="cmd for cmd in cmdJson" name= "CapabilityCmd" required>

In Typescript code:

this.http.get(URL, options)
      .pipe(map ((response) => response.json()))
      .subscribe((res) => {
        this.commandResponse = res;
        this.cmdJson = this.commandResponse.commands;
        console.log("commands:", this.cmdJson);
      });

I notice that cmdJson is showing the correct response(ie;

{“key1” : { }, “key2”: { }}

) in console but not populating in drop-down box.

There is no ng-options available in angular, you are using angularjs syntax, instead use ngFor

<select [(ngModel)]="selectedName">
    <option *ngFor="let cmd of cmdJson" [value]="cmd ">
      {{cmd}}
    </option>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM