gpt4 book ai didi

javascript - 如何在 Angular 2中的模板 View 内进行嵌套循环

转载 作者:行者123 更新时间:2023-11-28 17:15:22 25 4
gpt4 key购买 nike

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

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

关于javascript - 如何在 Angular 2中的模板 View 内进行嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com