【问题标题】:how to retrieve the value from nested object arrays angular如何从嵌套对象数组中检索值
【发布时间】:2020-08-31 20:27:24
【问题描述】:

我有一个带有嵌套数组的对象数组,如下所示。如何使用 ngFor 在表中打印嵌套数组值。 数组如下所示:

我正在使用表格来打印这些值,以便将表格导出到 Excel 工作表。

表格如下:

   <table class="table table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>Hours</th>
                    <th>Dates</th>
                    <th>Project Codes</th>
                </tr>
            </thead>
            <tbody class="tbody" *ngFor="let value of array; let i = index">
                <tr *ngFor="let item of array[i].item; let dateValue of array[i].datesArray; let h of array[i].hours">
                    <td>{{h}}</td>
                    <td>{{dateValue}}</td>
                    <td>{{value.projectCodeInput}}</td>
                </tr>
            </tbody>
        </table>

我在 ngFor 的单个标签上使用多个数组,如下所示: {*ngFor="let item of array[i].item; let dateValue of array[i].datesArray; let h of array[i].hours"} 我知道这是错误的方式,但不知何故,两个地方的输出中都会打印小时数,覆盖第二列中的 dateValue。

有没有办法在同一元素(TABLE)中打印小时、dateValue 数组中的值?

【问题讨论】:

    标签: html arrays angular ngfor


    【解决方案1】:

    您可以将let i=index 移动到内部循环并使用它来获取值,而不是对*ngFor 指令进行多个输入。

    我假设所有子数组总是等长,即hoursdatesArrayitem 数组总是等长。

    如果您希望将projectCodeInput 属性跨越多行,因为它对于父数组的每个元素都是相同的,您可以使用[attr.rowspan] 属性和first 局部变量来实现这一点@987654330 @指令。检查是为了确保 span 元素在循环中只呈现一次。

    <table class="table table-bordered">
      <thead class="thead-dark">
        <tr>
          <th>Hours</th>
          <th>Dates</th>
          <th>Project Codes</th>
        </tr>
      </thead>
      <tbody class="tbody" *ngFor="let element of arr">
        <tr *ngFor="let item of element.item; let i=index; let f=first">
          <td>{{element.hours[i]}}</td>
          <td>{{element.datesArray[i]}}</td>
          <td *ngIf="f" [attr.rowspan]="element.item.length">{{element.projectCodeInput}}</td>
        </tr>
      </tbody>
    </table>
    

    工作示例:Stackblitz

    【讨论】:

      【解决方案2】:

      您可以使用内部循环的索引并通过该索引获取值z

      <table class="table table-bordered">
          <thead class="thead-dark">
              <tr>
                  <th>Hours</th>
                  <th>Dates</th>
                  <th>Project Codes</th>
              </tr>
          </thead>
          <tbody class="tbody" *ngFor="let value of array; let i = index">
              <tr *ngFor="let item of array[i].item; let z = index">
                  <td>{{array[i].hours[z]}}</td>
                  <td>{{array[i].datesArray[z]}}</td>
                  <td>{{value.projectCodeInput}}</td>
              </tr>
          </tbody>
      </table>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-11-19
        • 1970-01-01
        • 2017-08-01
        • 1970-01-01
        • 2021-12-31
        • 2021-11-04
        • 2021-11-15
        相关资源
        最近更新 更多