【问题标题】:How to get Index Image in ng-bootstrap Carousel如何在 ng-bootstrap Carousel 中获取索引图像
【发布时间】:2019-06-13 22:57:53
【问题描述】:

我已经使用 ng-bootstrap https://ng-bootstrap.github.io/#/components/carousel/examples#navigation 在角度版本 7 中显示轮播。我想获取图像的当前索引。我需要它来显示与图像对应的背景颜色。 然后我看到一个事件(幻灯片),它向我展示了一些可用于确定图像索引的元信息。 (我总共有 3 张图片)

{"prev":"ngb-slide-1","current":"ngb-slide-2","direction":"left"}

当我导航到其他页面并返回时的一个问题。 元信息从 ngb-slide-4 而不是 ngb-slide-0 开始。

在此处查看我的链接演示 https://angular-ndxybr.stackblitz.io/

回到我的问题,当图像滑动时如何获取图像的索引? 非常感谢。

我可以通过从 ngb-slide-2 或 ngb-slide-5(下一次)中提取数字来解决问题。 index = number % 3,但万一图片数量变化不正确

【问题讨论】:

    标签: angular


    【解决方案1】:

    NgbSlide 指令有一个 id 输入属性,如果您不设置它,它会自动生成。但是,您可以设置它以确保它始终为您提供图像索引:

    <ngb-carousel *ngIf="images" (slide)="onSlide($event)">
      <ng-template *ngFor="let image of images; let i = index" ngbSlide [id]="'slideId_' + i">
        <img [src]="image" alt="Random slide">
      </ng-template>
    </ngb-carousel>
    

    然后可以从id中提取索引:

    onSlide(event) {
      const imageIndex = parseInt(event.current.replace("slideId_", ""), 10);
      ...
    }
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

    • 谢谢。工作正常。感觉有点像解决方法。旋转木马中没有正式跟踪羞耻指数。
    【解决方案2】:

    您可以像这样使用ngbSlide 的(slid) 回调:

    在你的component.html:

    <ngb-carousel>
      <ng-template (slid)="activeIndex = i" *ngFor="let slide of slides; index as i" ngbSlide>
        <div>
          <!-- Slide content -->
          activeIndex: {{activeIndex}}
        </div>
      </ng-template>
    </ngb-carousel>
    

    在你的component.ts:

    activeIndex: number = 0;
    slides: any[] = []; // e.g. img urls
    

    示例:延迟加载图片

    这样的应用可以是在轮播中延迟加载图片:

    在你的component.html:

    <ngb-carousel *ngIf="imgUrls.length>0">
      <ng-template (slid)="activeImageIndex = i" *ngFor="let imageUrl of imgUrls; index as i" ngbSlide>
        <img *ngIf="i === activeImageIndex || i === activeImageIndex+1 || i === activeImageIndex-1 || (activeImageIndex === 0 && i === imgUrls.length-1) || (activeImageIndex === imgUrls.length-1 && i===0)" [src]="imageUrl">
      </ng-template>
    </ngb-carousel>
    

    注意:&lt;img&gt; 标签中的*ngIf 将确保将加载以下图像:

    • 上一个(或最后一个,如果当前是第一个)
    • 当前的
    • 下一个(或第一个,如果当前是最后一个)

    如果您使用动画,这将实现平滑过渡。

    在你的component.ts:

    activeImageIndex : number = 0;
    imgUrls = ['https://picsum.photos/id/1/300/200', 'https://picsum.photos/id/2/300/200', 'https://picsum.photos/id/3/300/200']; // e.g. img urls
    

    这样,只会下载当前和下一个图像,从而减少流量。

    【讨论】:

      猜你喜欢
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 2012-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多