【问题标题】:How to set the selected image as the first image to show in a bootstrap carousel in Angular?如何将所选图像设置为在 Angular 的引导轮播中显示的第一个图像?
【发布时间】:2021-10-01 04:42:12
【问题描述】:

我创建了一个小的 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

任何帮助将不胜感激。

【问题讨论】:

  • 尝试在视图初始化生命周期设置活动索引
  • 我尝试使用 view init 生命周期钩子,不幸的是它也没有字。
  • 你需要为每个滑块赋予属性[id]-是一个字符串-<ng-template ngbSlide [id]="one">..</ng-template>,然后你可以使用this.activeId="one"

标签: javascript angular bootstrap-4 angular-ui-bootstrap


【解决方案1】:

尝试在轮播构造函数中使用图像,因为它是您刚刚移动的数组。 您选择索引并将与该索引匹配的幻灯片移动到第一个位置。我建议在轮播模板中使用 *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);
      }
    });
  }

希望对你有所帮助;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-19
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多