【问题标题】:Populate the data in drop-down from a GET json response- Angular4从 GET json 响应中填充下拉列表中的数据 - Angular4
【发布时间】:2018-12-30 10:30:04
【问题描述】:

我正在尝试在命令的下拉列表中显示 json 键/字段;这是对象类型(见下面的json) 例如:“key1”、“key2”应该出现在下拉列表中。最初使用 *ngfor 但它给出了错误-“ngfor 仅支持绑定可迭代对象,例如数组”。 由于我的 json 不包含数组,因此尝试使用 ng-options 但无法填充下拉列表。我的 json 看起来像:

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

html代码:

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

在打字稿代码中:

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

我注意到 cmdJson 显示了正确的响应(即;

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

) 在控制台中但不填充到下拉框中。

【问题讨论】:

    标签: html angular typescript ng-options


    【解决方案1】:

    在 Angular 中有 no ng-options 可用,您使用的是 angularjs 语法,而不是使用 ngFor

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

    【讨论】:

    • 当然,但这就是我在在线教程/博客上找到的基于我的 json 遇到的场景。我已经使用 ngFor 尝试过这种方式,但出现错误-“错误:找不到类型为 'object' 的不同支持对象 '[object Object]'。NgFor 仅支持绑定到 Iterables,例如数组。”不过感谢您的快速回复!
    • 我最终将对象存储为一个数组,使用 Object.keys 返回数组中的 json 键,然后使用 *ngFor 在下拉列表中显示值。这行得通!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2021-06-19
    • 2021-04-04
    相关资源
    最近更新 更多