【问题标题】:How to do nested loops inside template view in angular2+如何在角度2中的模板视图内进行嵌套循环
【发布时间】:2018-12-02 15:16:33
【问题描述】:

我需要在我的模板中查看不同的数组索引及其值。我有这个对象:

vegetables = [
    {name: 'Carrot', type: 'vegetable'},
    {name: 'Onion', type: 'vegetable'},
    {name: 'Potato', type: 'vegetable'},
    {name: 'Capsicum', type: 'vegetable'}],
    [
      {name: 'Carrotas', type: 'vegetable'},
      {name: 'Onionas', type: 'vegetable'},
      {name: 'Potatoas', type: 'vegetable'},
      {name: 'Capsicumas', type: 'vegetable'}]

我这样做:

 <li class="list-group-item list-group-item-action list-group-item-success" [draggable] *ngFor="let items of [vegetables[0]]"
                        [dragClass]="'active'" [dragTransitClass]="'active'" [dragData]="item" [dragScope]="item.type" [dragEnabled]="dragEnabled">
                        {{item.name}}
                    </li>

但是[vegetables[0]] 只从列表中输出“Carrot”,仅此而已。相反,我需要它输出第一个数组及其所有内容,然后在第二次迭代中,输出带有“Carrotas”、“Onionas”等的第二个数组。如何实现这一点?

0 将被替换为 i,每次遍历 vegetables 内的不同列表数组时都会递增。

【问题讨论】:

    标签: javascript arrays angular loops property-binding


    【解决方案1】:

    首先,您提供的数组是错误的。我假设它会是这样的:

    vegetables = [[
    {name: 'Carrot', type: 'vegetable'},
    {name: 'Onion', type: 'vegetable'},
    {name: 'Potato', type: 'vegetable'},
    {name: 'Capsicum', type: 'vegetable'}],
    [
      {name: 'Carrotas', type: 'vegetable'},
      {name: 'Onionas', type: 'vegetable'},
      {name: 'Potatoas', type: 'vegetable'},
      {name: 'Capsicumas', type: 'vegetable'}]]
    

    如果我理解正确,要么您必须使用 *ngIf 编写索引(例如检查索引是奇数还是偶数),或者将它们减少为一个。例如:

    const vegetablesReduced = vegetables.reduce((r, x) => [...r, ...x], []);
    

    这将创建如下数组:

    vegetablesReduced = [
      {name: 'Carrot', type: 'vegetable'},
      ...
      {name: 'Carrotas', type: 'vegetable'},
      ...
    ];
    

    编辑:啊..我只看到您的问题仅在于数组定义。您在那里创建数组的方式是错误的,因为您只创建第一个而第二个被忽略(javascript ...)。尝试按照我提供的更改数组,看看它是否有效。

    EDIT2:它应该是 2D 数组,而您只有 1D (并且也有错误,因为 1D 数组不能拆分为多个数组)您缺少的只是将整个东西包装到另一个数组中并且它会起作用的。

    【讨论】:

    • 是的,这是可行的,谢谢。我需要更多地了解 js 数组等等。现在我可以用这行代码[vegetables[0][0]] 得到Carrot。现在我只需要弄清楚如何嵌套 ngFor 循环并将其绑定到 [draggable] 指令以打印输出 0 数组内的所有蔬菜名称,然后打印出第一个数组内的所有蔬菜名称,依此类推..
    • 我认为你必须使用像*ngFor="let item of vegetables[INDEX]" 这样的东西,它将返回索引行中的所有蔬菜。所以item 变成了你所期待的。
    • 就像注释一样,reduce 也可以是这样的:const vegetablesReduced = vegetables.reduce((r, x) =&gt; r.concat([...x]), []);,你会得到相同的结果。
    • 是的。这是更快的变体。或者您可以使用更快:r.concat(x)
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 2019-04-04
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多