首页 > 解决方案 > 循环嵌套的对象数组

问题描述

我很难尝试使用 ng7 遍历嵌套对象数组

这是我拥有的数据:

data = { 
    'title1': [
    {
      active: true, 
      id: 1 
    },
  {
      active: true, 
      id: 2 
    },
  {
      active: true, 
      id: 3 
    },
  {
      active: true, 
      id: 4 
    }],
  'title2': [
   {
      active: true, 
      id: 1 
    },
  {
      active: true, 
      id: 2 
    },
  {
      active: true, 
      id: 3 
    },
  {
      active: true, 
      id: 4 
    }]              
}

我需要打印标题,例如“title1”,其余数据应该嵌套显示,问题是,每当我采用这种方法时,一切看起来都很好:

 <ul>
    <li *ngFor="let item of data| keyvalue">
        <p>{{ item.key }}</p> 
        <p *ngFor="let children of item.value | keyvalue" >
            {{ children.value.id}}
        </p>
    </li>
  </ul>

但是每当我将布局切换到这样的输入复选框时:

       <ul>
        <li *ngFor="let item of data| keyvalue">
            <p>{{ item.key }}</p> 
            <label>
                <input type="checkbox" name="events" *ngFor="let children of item.value | keyvalue" />
                event item {{ children.value.id}}
            </label>
        </li>
      </ul>

我在浏览器的控制台上收到以下错误,但没有任何渲染:

错误类型错误:无法在 Object.eval [as updateRenderer] 处读取未定义的属性“值”

{{ item.key }}

任何想法?我确定我错过了一些愚蠢的东西,

标签: javascriptarraysangularobjectngfor

解决方案


当您children引用它时,您的引用不在范围内,因为该event item {{children.value.id}}字符串不包含在<input>元素中。

<label>在你的而不是你的<input>元素上定义循环:

<ul>
  <li *ngFor="let item of data | keyvalue">
      <p>{{ item.key }}</p> 
      <label *ngFor="let children of item.value | keyvalue">
          <input type="checkbox" name="events" />
          event item {{children.value.id}}
      </label>
  </li>
</ul>

推荐阅读