Angular Shadow Dom组件内Swiper的pagination分页圆点不显示问题
根因分析
- 你启用了
ViewEncapsulation.ShadowDom后,组件内部的DOM元素会被隔离在ShadowRoot中,Swiper默认从全局document查找你配置的.elem-swiper-pagination选择器,无法命中ShadowDom内部的元素,因此不会渲染分页圆点。 - ShadowDom会隔离全局样式,Swiper的默认分页样式如果没有导入到组件样式文件中,就算成功生成了分页元素也不会显示。
- 你提供的HTML代码存在两个语法问题:分页div缺少闭合标签、轮播卡片的样式类
h-80w-full漏了空格,应为h-80 w-full。
解决方案
步骤1:修改HTML代码,给分页元素加模板引用,补全语法错误
<swiper [config]="sliderConfig"> <ng-template swiperSlide *ngFor="let image of images.sliderImages" > <div class="bg-no-repeat bg-white bg-cover bg-center h-80 w-full rounded" [ngStyle]="{ 'background-image': 'url(' + image + ')' }" ></div> </ng-template> </swiper> <!-- 新增#paginationRef模板引用,补全闭合标签 --> <div #paginationRef class="elem-swiper-pagination flex justify-center my-1"></div>
步骤2:修改组件TS代码,直接传分页元素实例给Swiper配置
不要传选择器字符串,直接传入已经获取到的ShadowDom内的元素实例,绕过Swiper的全局DOM查询逻辑:
import { Component, ViewChild, ElementRef, AfterViewInit, ViewEncapsulation } from '@angular/core'; import { SwiperOptions } from 'swiper'; @Component({ selector: 'app-elem', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], encapsulation: ViewEncapsulation.ShadowDom }) export class AppElemComponent implements AfterViewInit { // 获取分页元素的引用 @ViewChild('paginationRef') paginationEl!: ElementRef<HTMLElement>; sliderConfig!: SwiperOptions; ngAfterViewInit(): void { // 视图初始化完成、元素引用生成后再初始化Swiper配置 this.sliderConfig = { slidesPerView: 1, slidesPerColumn: 2, followFinger: false, longSwipes: true, shortSwipes: true, spaceBetween: 15, slidesPerColumnFill: 'row', updateOnWindowResize: true, observer: true, observeParents: true, slidesPerGroup:2, pagination: { // 直接传入DOM元素实例,无需选择器 el: this.paginationEl.nativeElement, clickable: true, type: 'bullets', bulletActiveClass: 'swiper-pagination-bullet-active', bulletClass: 'swiper-pagination-bullet', }, }; } }
步骤3:在组件样式文件中导入Swiper基础样式
ShadowDom会隔离全局样式,需要把Swiper的样式导入到组件内部样式中才能生效:
/* app.component.scss 顶部添加 */ @import 'swiper/swiper-bundle.min.css'; /* 可自定义分页样式 */ .swiper-pagination-bullet { width: 8px; height: 8px; background-color: #ccc; opacity: 1; margin: 0 4px; } .swiper-pagination-bullet-active { background-color: #333; }
内容的提问来源于stack exchange,提问作者Arjun C
相关产品推荐
相关产品推荐

