如何在 Angular 2 的模板视图中做嵌套循环

How to do nested loops inside template view in angular2+

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

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.

中的不同列表数组

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

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:它应该是二维数组,而你只有一维(而且也有错误,因为一维数组不能拆分成多个数组)你所缺少的只是将整个东西包装成另一个数组,它将起作用。