繁体   English   中英

如何将所选图像设置为在 Angular 的引导轮播中显示的第一张图像?

[英]How to set the selected image as the first image to show in a bootstrap carousel in Angular?

我创建了一个小的 tuto 代码,其中有一张卡片列表。 在这些卡片上,我有一个点击事件,它传递这张卡片的索引,稍后我将使用它来设置要在轮播中显示的第一个图像。 该索引通过与创建的组件共享的服务过去。

现在该索引已成功通过,当我在轮播组件中收到它时,将它放入<ngb-carousel [activeId]="activeIndex"> ,如文档中所述

 /**
 * The slide id that should be displayed **initially**.
 *
 * For subsequent interactions use methods `select()`, `next()`, etc. and the `(slide)` output.
 */
 activeId: string;

但是,我所做的没有任何效果,因为轮播仍然每次都向我显示第一张图像。 我错过了什么吗?

在这里你可以找到源代码: https : //github.com/agentjoseph007/modal-carousel

任何帮助都感激不尽。

尝试在 carousel 构造函数中处理图像,因为它是您刚移动的数组。 您选择索引,然后将与该索引匹配的幻灯片移动到第一个位置。 我建议在您的轮播模板中使用 *ngFor。

在 carousel.component.html 中

<ngb-carousel (slide)="onSlide($event)">
  <ng-container *ngFor="let slide of slides; let index = index">
    <ng-template ngbSlide [id]="index">
      <div class="picsum-img-wrapper">
        <img [src]="slide.image" [alt]="slide.alt">
      </div>
      <div class="carousel-caption">
        <h3>{{slide.label}}</h3>
        <p>{{slide.content}}</p>
      </div>
    </ng-template>
  </ng-container>
</ngb-carousel>

也许社区可能对如何处理幻灯片有其他建议,但我向您建议此代码和 carousel.component.ts

  photos = [944, 1011, 984].map((n) => `https://picsum.photos/id/${n}/900/500`);
  slides = [
    {
      index: 0,
      image: this.photos[0],
      label: 'First slide label',
      content: 'Nulla vitae elit libero, a pharetra augue mollis interdum.',
      alt: 'my first slide image'
    },
    {
      index: 1,
      image: this.photos[1],
      label: 'Second slide label',
      content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      alt: 'my first slide image'
    },
    {
      index: 2,
      image: this.photos[2],
      label: 'Third slide label',
      content: 'Praesent commodo cursus magna, vel scelerisque nisl consectetur.',
      alt: 'my first slide image'
    }
  ];

  ...

  constructor(private imageHandlerService: ImageHandlerService) {
    console.log('CarouselComponent');
    console.log(this.imageHandlerService.selectedIndex);
    this.slides.forEach((element, i) => {
      if (element.index === this.imageHandlerService.selectedIndex) {
        this.slides.splice(i, 1);
        this.slides.unshift(element);
      }
    });
  }

希望能帮助到你 ;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM