【问题标题】:Angular2 : Iterate *ngfor particular times [ Error: NgFor only supports binding to Iterables such as Arrays. ]Angular2:迭代 *ngfor 特定时间 [错误:NgFor 仅支持绑定到可迭代对象,例如数组。 ]
【发布时间】:2016-07-30 04:45:13
【问题描述】:

我正在尝试在特定时间(角度 2.0.0-rc.4)迭代 for 循环。例如。 5次或10次..

home.component.html:

   {{arr_length}} //printing 10 i.e. I have specified in home.component.ts

        <tr *ngFor="let i of arr_length ; let ind = index">
            <td>
               //code goes here...
            </td>
        </tr>

但在 *ngFor 中会抛出错误:NgFor only supports binding to Iterables such as Arrays.

我是角度的新手。任何帮助,将不胜感激。

home.component.ts :

import { Component } from '@angular/core';
@Component({
  selector: 'home',
  templateUrl: '../templates/home.component.html',
  directives: [],
  providers: []
})
export class HomeComponent
{
    arr_length: number;
    constructor() 
    {
        this.arr_length = 10;
    }
}

【问题讨论】:

  • 让我们看看您的组件代码。 home.component.ts
  • 你的问题的答案就在错误的文本中。
  • @Casey:当我使用数组时,它工作正常但是如何在不使用任何数组的情况下迭代特定时间(例如 10 或 15)?
  • @Que : 我已经包含 home.component.ts 代码

标签: angular ngfor


【解决方案1】:

您正在迭代一个数字。我认为您想遍历数组,因此从您的组件将绑定更改为仅元素数组而不是长度。 如果你只想循环 n 次。 您可以创建 n 个数字的数组。并遍历该数组。 这是循环 10 倍的示例 在您的组件上:

 export class HomeComponent
    {
        arr_length;
        constructor() 
        {
            this.arr_length = Array(10).fill().map((x,i)=>i);;
        }
    }

在您的模板上

 <tr *ngFor="#number of arr_length">
       <td>
            //code goes here...
      </td>
</tr>

【讨论】:

  • 感谢您的回答。是的,如果我遍历一个数组,那么它工作正常。但是假设我想迭代一个特定的数字而不需要任何数组的帮助,那么我该怎么做呢?
  • 是的,这是有效的。谢谢你。但是你能解释一下constructor()里面的代码吗?
  • @vedu :在构造函数中发生了什么: 1 - 创建大小为 10 的空数组 --> Array(10) 2- 用数组索引的数字填充它fill() 调用和 3- map() 运算符映射数组的索引以填充元素
  • 哦..太好了。再次感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
相关资源
最近更新 更多