Angular 2 - 使用动态属性循环对象

时间:2017-03-15 15:01:47

标签: angular object

我需要在angular2中循环对象。

我的对象看起来像这样

object = { description: "hi", otherthing: "hello" };

所以这个对象是动态的,我需要遍历每个属性(属性的数量可以改变)

这是我到目前为止的代码

<ul *ngFor="let item of errorMessages | keys" class="list-group">
    <li class="list-group-item">
        {{ item | json }}
    </li>
</ul>

目前向我显示"description"但是当我尝试打印{{ errorMessages.item }}时,它没有显示任何内容。

我假设我的语法错误,因为item不是对象的属性,但是打印它的正确方法是什么呢?

2 个答案:

答案 0 :(得分:2)

您不能像以下那样访问对象的动态属性:

试试这个:

{{ errorMessages[item] }}

答案 1 :(得分:0)

在模板代码Angular6 +版本中,您可以按如下所示使用KeyValue管道来获取项作为项:

<div *ngFor="let keyValuePair of someObject | kevvakye">
  This is the key {{keyValuePair.key}} and this is the value {{keyValuePair.val}}.
</div>

您可以像下面在组件/打字稿代码中给出的那样遍历对象属性:

for (let key in this.ObjectWithAttributes) {
    if (this.concatAttributeWithValues!== '') {
        this.concatAttributeWithValues+= '\r\n';
    }
    this.concatAttributeWithValues+= key + ' : ' + this.ObjectWithAttributes[key];
}