TypeError: slideArr[0] is undefined on carousel using *ngFor

TypeError: slideArr[0] is undefined on carousel using *ngFor

我一直在努力寻找我做错了什么,也许你能帮我。

我正在尝试在 ngb-carousel 模板上使用 *ngFor="let image of card.carouselImgs" 显示轮播,如下所示:

 <ngb-carousel>
     <template *ngFor="let image of card.carouselImgs" ngbSlide  >
       <img src="{{image.imgUrl}}" alt="{{image.imgAlt}}">
     </template>
   </ngb-carousel>

但我收到此错误:

ERROR TypeError: slideArr[0] is undefined
Stack trace:
NgbCarousel.prototype._getNextSlide@http://localhost:4200/vendor.bundle.js:43189:9
NgbCarousel.prototype.cycleToNext@http://localhost:4200/vendor.bundle.js:43149:76
NgbCarousel.prototype._startTimer/this._slideChangeInterval<@http://localhost:4200/vendor.bundle.js:43174:67
ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:3176:17
onInvokeTask@http://localhost:4200/vendor.bundle.js:4326:28
ZoneDelegate.prototype.invokeTask@http://localhost:4200/polyfills.bundle.js:3175:17
Zone.prototype.runTask@http://localhost:4200/polyfills.bundle.js:2943:28
ZoneTask/this.invoke@http://localhost:4200/polyfills.bundle.js:3238:28
timer@http://localhost:4200/polyfills.bundle.js:4433:17

所以我检查了数据是否有问题,但没有,这样做时一切正常:

<div *ngFor="let image of card.carouselImgs">
  imgUrl: {{image.imgUrl}} 
  imgAlt: {{image.imgAlt}}
</div>

输出:

imgUrl: ../../assets/briefcase/1.jpg imgAlt: Hello
imgUrl: ../../assets/briefcase/2.jpg imgAlt: Hello
imgUrl: ../../assets/briefcase/3.jpg imgAlt: Hello

所以我认为是 ngb-carousel 的一个错误。有什么帮助吗? 提前致谢:)

尝试从 ng-template 移动 ngFor

可能是这样的:

  <ng-container *ngFor="let image of card.carouselImgs">
      <ng-template ngbSlide>....</ng-template>
  </ng-container>

如果没有清晰的重现场景,很难说出任何明确的内容,但需要注意的一件事是,您 必须 使用具有最新的 <ng-template> 元素(1.0.0-alpha.25在撰写本文时)发布 https://ng-bootstrap.github.io/

因此您的示例将转换为:

<ngb-carousel>
     <ng-template *ngFor="let image of card.carouselImgs" ngbSlide  >
       <img src="{{image.imgUrl}}" alt="{{image.imgAlt}}">
     </ng-template>
   </ngb-carousel>

这是从 demo page showing things working with <ng-template>: http://plnkr.co/edit/2ec6OwwxCEawWNVaqEpk?p=preview 派生出来的一个 plunker - 您可能想要派生这个 plunker 以提供清晰的重现场景并在需要时扩展您的问题。