You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular用ngFor生成多个owl-carousel-o时resize页面卡片消失如何解决

问题原因

所有轮播组件共用同一个customOptions对象引用,owl-carousel-o的响应式逻辑在窗口resize触发时,会修改传入的options对象完成尺寸适配,多个轮播实例同时修改同一个引用会导致状态冲突,最终计算展示条目数异常,卡片消失。移除responsive配置后没有动态修改options的逻辑,所以功能正常。

解决方法

1. 为每个轮播实例分配独立的options对象

不要共用全局的单个customOptions,改为每次生成独立的配置对象:
在组件ts中新增配置生成方法:

// 原单个customOptions属性删除,替换为以下方法
getCustomOptions(): OwlOptions {
  return {
    loop: false,
    mouseDrag: true,
    touchDrag: true,
    pullDrag: false,
    dots: false,
    navSpeed: 700,
    navText: ["",""],
    responsive: {
      0: {
        items: 1
      },
      400: {
        items: 2
      },
      740: {
        items: 3
      },
      940: {
        items: 4
      }
    },
    nav: true
  }
}

如果追求更好的性能,可以在拿到demoDataCatVideo数据时,提前为每一项预先生成配置:

// 数据请求完成后执行
this.demoDataCatVideo = this.demoDataCatVideo.map(item => ({
  ...item,
  carouselOptions: this.getCustomOptions()
}))

2. 为每个轮播组件添加唯一ID

避免多个轮播实例的内部DOM查找、事件绑定冲突,修改模板代码:

<ng-container *ngFor="let item of demoDataCatVideo; let i = index">
    <div class="content-carousel">
        <h2>{{item.category.label}}</h2>
        <!-- 新增唯一id,options绑定独立配置 -->
        <owl-carousel-o [id]="'carousel-' + i" [options]="item.carouselOptions ?? getCustomOptions()">
            <ng-container *ngFor="let card of item.children | slice:0:15">
                <ng-template carouselSlide [id]="card.id">
                    <div class="single-item">
                        <div class="box-img">
                            <img [src]="card.thumbnail" alt=""/>
                        </div>
                        <div class="box-meeting-info">
                            <div class="box-article">
                                <p class="name-product">{{card.name}}</p>
                            </div>
                            <div class="date-start">
                                <p>{{card.startDate | date:'dd-MM-yyyy H:mm:ss'}}</p>
                            </div>
                        </div>
                    </div>
                </ng-template>
            </ng-container>
        </owl-carousel-o>
    </div>
</ng-container>

可选补充配置

如果以上修改后仍偶现异常,可以在options中新增responsiveBaseElement配置项,指定轮播自身容器作为响应式计算基准,避免全局尺寸计算误差。

内容的提问来源于stack exchange,提问作者corsaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:30:03