【问题标题】:Why is the *ngFor loop in the code segment not being entered?为什么没有进入代码段中的*ngFor循环?
【发布时间】:2020-03-07 04:43:29
【问题描述】:

即使数组 subBanner1 包含数据,也永远不会进入以下 ngFor 循环:

<div class="col-6 d-flex d-lg-flex flex-column justify-content-lg-center shop-all"
        *ngFor="let image of images.subBanner1">
        <img class="img-fluid d-lg-flex" src="assets/img/{{image}}" alt="image">
    </div>

这是 subBanner1 数组:

subBanner1: ['05-0320-w1-Women-Main2.jpg', '05-0320-w1-Men-Main2.jpg']

另一方面,当我如下所示直接定位数组的特定元素时,它会显示图像。

<div class="col-6 d-flex d-lg-flex flex-column justify-content-lg-center shop-all">
        <img class="img-fluid d-lg-flex" src="assets/img/{{images.subBanner1[0]}}">
    </div>

获取subBanner1数组的代码:

private getHomeStaticData = () => {
const homeSelector = (state) => {return (state.home)};
let home$ = this.store.select(homeSelector);

home$.subscribe(homeStaticData => {
  this.images = homeStaticData.images
  console.log('images', this.images)
  console.log('images.subBanner1', this.images.subBanner1)
})    
 }

subBanner1 初始化:

const initialState = {
    images: {
        mainBanner: '05-0320-w1-HeroClearout2.jpg',
        subBanner1: ['05-0320-w1-Women-Main2.jpg', '05-0320-w1-Men-Main2.jpg']
    }
   }

【问题讨论】:

  • 你在使用OnPush策略吗?
  • 我不知道 OnPush 策略是什么。它是一个新的 Angular 构造吗?
  • 代替&lt;img&gt;,你能尝试打印所有元素吗?
  • 不,它是组件装饰器中的一个属性。您能否在填充数组的位置添加代码?
  • @JacopoSciampi 我已经添加了获取数组的代码。

标签: angular


【解决方案1】:

因为你没有使用*ngFor里面的索引策略

<div class="col-6 d-flex d-lg-flex flex-column justify-content-lg-center shop-all"
    *ngFor="let image of images.subBanner1; index as i">
    <img class="img-fluid d-lg-flex" src="assets/img/{{image[i]}}" alt="image">
</div>

添加了index as i 来为您的数组提供索引。还添加了{{image[i]}},它在遍历图像数组时将具有相应的索引。

Angular documentation 中详细了解您可以在*ngFor 中拥有的所有局部变量。


编辑 经过一些调试,我认为上面不是要走的路,从您在问题中提供的内容可以看出,您实际上并没有将数组分配给subBanner1。应该是=,而不是:

subBanner1: ['05-0320-w1-Women-Main2.jpg', '05-0320-w1-Men-Main2.jpg']

应该是

subBanner1 = ['05-0320-w1-Women-Main2.jpg', '05-0320-w1-Men-Main2.jpg']

我制作了a StackBlitz demo 来显示上述修改并查看实际问题是什么。

【讨论】:

  • 没用。问题是没有输入 ngFor 循环,所以即使我按索引定位图像,仍然没有输入循环。
  • @Roy - image 不是已经指向数组项了吗?为什么要为其附加索引?我会理解{{images.subBanner1[i]}},但我不理解{{image[i]}}
  • @ConnorsFan 是的,我认为你是对的。让我把事情说清楚。
  • @Roy 您的代码有效,但不能解决我的问题。如果我像这样从您的代码中删除索引:
    ,它仍然有效。这正是我在没有索引的代码中所做的。出于某种原因,两者都不适合我。如我的代码所示,我已经实现了 ngFor 数百次并且它们有效。我开始认为这与 Angular 的最新版本有关。
  • 您是否完整阅读了我的编辑?它提到了数组分配。
猜你喜欢
相关资源
最近更新 更多
热门标签