I am using Swiper for angular and using Angular Swipper wrapper with it. I am trying to add a button which onclick
swipes to next slide.
But I have no idea how to get Swiper instance and how to call slidenext
function. How can I do the same? Thanks in advance.
Angular 12 / Swiper 6.8.1
.html
<swiper [slidesPerView]="4" [spaceBetween]="50">
<ng-template swiperSlide>
<app-product-item></app-product-item>
</ng-template>
</swiper>
<button (click)="swipeNext()">Prev</button>
<button (click)="swipePrev()">Next</button>
.ts
@ViewChild(SwiperComponent) swiper: SwiperComponent;
swipePrev() {
this.swiper.swiperRef.slidePrev();
}
swipeNext() {
this.swiper.swiperRef.slideNext();
}
While using ngx-wrapper, you can use either component or directive approach. You can access swiper reference with @ViewChid as mentioned above to access swiper methods.
Example of swiper-wrapper
TS
@ViewChild(SwiperDirective) directiveRef?: SwiperDirective;
@ViewChild(SwiperComponent, { static: false }) compRef?:SwiperComponent;
swiperConfig = {
initialSlide: 0
};
nextSlide() {
this.directiveRef.nextSlide();
}
previousSlide() {
this.directiveRef.prevSlide();
}
nextSlideComp() {
this.compRef.directiveRef.nextSlide();
}
previousSlideComp() {
this.compRef.directiveRef.prevSlide();
}
HTML
<!-- Directive usage -->
<div class="swiper-container" [swiper]="swiperConfig">
<div class="swiper-wrapper">
<div class="swiper-slide" *ngFor="let slide of slides">
....your content
</div>
</div>
</div>
<!-- Navigation -->
<button (click)="nextSlide()">Previous</button>
...
<!-- Component usage -->
<swiper [config]="swiperConfig">
<div *ngFor="let slide of slides">
...your content
</div>
</swiper>
<!-- Navigation -->
<button (click)="nextSlideComp()">Previous</button>
...
NOTE: ngx-swiper-wrapper is no longer required since swiperJs has its own angular components. SwiperJS - angular component
You can use swiper event that returns swiper instance as soon as posible.
<swiper (swiper)="..." (slideChange)="..." </swiper>
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