我正在尝试对 Angular 15 应用程序中加载的 Swiper 9 Web 组件滑块进行样式化。我遵循了官方文档。特别是,我想通过
injectStyles
参数将样式注入滑块组件的 Shadow DOM。
我的 Swiper 配置是:
public config: SwiperOptions = {
modules: [Navigation],
navigation: true,
slidesPerView: 1,
injectStyles: [
`
:host .swiper-wrapper {background-color: red;}
:root {--swiper-theme-color: red;}
`,
],
};
但是,这些样式都没有被注入到影子 DOM 中。我注意到某些参数无法正常工作,例如
pagination: false
,这会导致滑块崩溃。
(ViewEncapsulation.None
似乎也不影响组件)。
这个bug是与框架有关还是与开发人员有关?
复制链接:StackBlitz
您需要将
init="false"
添加到您的组件中,这将使您注入的样式起作用。
<swiper-container swiperElement [config]="config" init="false">
<swiper-slide *ngFor="let i of [1,2,3]">
Slide {{i}}
</swiper-slide>
</swiper-container>
扩展尼尔斯给出的答案。这很大程度上受到了他的 Stackblitz 以及让它为我工作所需的东西的启发:
@ViewChild('swiperElement') swiperElement: any;
swiperConfig: SwiperOptions = {
init: true,
slidesPerView: 1.1,
loop: false,
spaceBetween: 10,
mousewheel: { forceToAxis: true },
breakpoints: this.breakpoints,
injectStyles: [':host .swiper { overflow: visible !important; }'],
};
ngAfterViewInit(): void {
this.initSwiper();
}
initSwiper() {
Object.assign(this.swiperElement.nativeElement, this.swiperConfig);
this.swiperElement.nativeElement.initialize();
}
还有 html:
<swiper-container #swiperElement init="false">
<swiper-slide *ngFor="let i of [1,2,3]">
Slide {{i}}
</swiper-slide>
</swiper-container>
稍微修改为不使用该指令。