I'm trying to migrate from ngx-swiper-wrapper
to swiper
in Angular 10. My approach is to have as modular solution as possible. Because of that I want to have a swiper-wrapper.component and swiper-slide.component.
Thanks to that I can pass different components into swiper and in case I need to modify how swiper-slide behave in the future I only need to do this in 1 place.
This approach worked pretty well in ngx-swiper-wrapper
however swiper
is ignoring ng-content
and I can render anything :-(
Here is a stackblitz to my current solution.
Root.component.html
<app-swiper-carousel [options]="virtualConfig">
<ng-container *ngFor="let slide of allSlides">
<app-swiper-slide>
<!-- I can render any component here -->
<div>
{{ slide.firstName + ' ' + slide.lastName }}
</div>
</app-swiper-slide>
</ng-container>
</app-swiper-carousel>
swiper-carousel.ts
<swiper #swip [config]="virtualConfig" [virtual]="true">
<!-- This doesnt' work :-( -->
<ng-content></ng-content>
<!-- Uncomment this to make it work -->
<!-- <ng-container *ngFor="let slide of virtualSlides.slides">
<ng-template swiperSlide>
<div>
{{ slide.firstName + ' ' + slide.lastName }}
</div>
</ng-template>
</ng-container> -->
</swiper>
*swiper-slide.component
<ng-template swiperSlide>
<ng-content></ng-content>
</ng-template>
Any idea if I'm doing something wrong or there is a bug in swiper? Does anyone have any idea how I can achieve my goal?
Create this two directive,
@Directive({
selector: '[appSwiperTemplate]',
})
export class SwiperTemplateDirective {}
@Directive({
selector: 'appSwiperContent',
})
export class SwiperContentDirective {
@ContentChild(SwiperTemplateDirective, { read: TemplateRef })
template!: TemplateRef<HTMLElement>;
}
Change ng-content with this.
<swiper [config]="config">
<ng-template *ngFor="let slide of contents" swiperSlide>
<ng-template [ngTemplateOutlet]="slide.template" [ngTemplateOutletContext]="{
$implicit: slide.template
}"></ng-template>
</ng-template>
</swiper>
add this line in .ts file
@ContentChildren(SwiperContentDirective, {
descendants: true,
})
contents!: QueryList<SwiperContentDirective>;
and use it like this.
<app-swiper-form>
<appSwiperContent *ngFor="let slide of slides">
<ng-template appSwiperTemplate>
.
. Your code
.
</ng-template>
</appSwiperContent>
</app-swiper-form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With