Пагинация / навигация Swiper с помощью настраиваемой кнопки в angular
5 ответов
Угловой 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();
}
При использовании ngx-wrapper вы можете использовать либо компонентный, либо директивный подход. Вы можете получить доступ к ссылке на swiper с помощью @ViewChid, как упоминалось выше, для доступа к методам swiper.
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>
...
ПРИМЕЧАНИЕ: ngx-swiper-wrapper больше не требуется, поскольку swiperJs имеет собственные угловые компоненты. SwiperJS - угловой компонент
Вы можете использовать событие swiper, которое возвращает экземпляр swiper при первой возможности.
<swiper (swiper)="..." (slideChange)="..." </swiper>
О пользовательской пагинации. Я использую Angular 12.HTML:
<section class="products-preview">
<div class="swiper products-preview__swiper">
<swiper [config]="swiperConfig">
<ng-template *ngFor="let item of slides"
class="swiper-slide"
swiperSlide>Some HTML</ng-template><!-- /swiper-slide -->
</swiper><!-- /swiper-wrapper -->
<div class="products-preview__pagination">
<div class="swiper-pagination"></div><!-- /swiper-pagination -->
</div><!-- /products-preview__pagination -->
</div><!-- /swiper -->
</section><!-- /products-preview -->
.ts-файл:
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import SwiperCore, {Pagination, SwiperOptions} from 'swiper';
import {ProductsPreviewSliderInterface} from "../../interfaces/products-preview-slider.interface";
import {ProductsPreviewSliderService} from "../../services/products-preview-slider.service";
SwiperCore.use([
Pagination,
]);
@Component({
selector: 'app-test-slider',
templateUrl: './test-slider.component.html',
styleUrls: ['./test-slider.component.scss'],
encapsulation: ViewEncapsulation.None // Ability to style child components
})
export class TestSliderComponent implements OnInit {
public slides: ProductsPreviewSliderInterface[] = [];
public swiperConfig: SwiperOptions = {};
constructor(private productsPreviewSliderService: ProductsPreviewSliderService ) {}
ngOnInit() {
// getSlides() service method returns an array of objects containing information about slides
const slidesArr = this.slides = this.productsPreviewSliderService.getSlides();
// swiper config, which we pass to the HTML
this.swiperConfig = {
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
// Create a pagination element
return '<div class="' + className + '">' +
'<div class="products-preview__inner">' +
'<img src="'+ slidesArr[index]['pagination']['icon'] +'" alt="" class="products-preview__icon">' +
'<div class="products-preview__name">'+ slidesArr[index]['pagination']['name'] +'</div>' +
'<div class="products-preview__txt">'+ slidesArr[index]['pagination']['text'] +'</div>' +
'</div>' +
'</div>';
},
}
};
}
}
HTML:
<button (click)="swipeToNextSlide()">Swipe to Next Slide</button>.
Составная часть:
public swipeToNextSlide() {
let index;
let ref;
if (this.type === "directive" && this.directiveRef) {
ref = this.directiveRef;
index = this.directiveRef.getIndex();
} else if (
this.type === "component" &&
this.componentRef &&
this.componentRef.directiveRef
) {
ref = this.componentRef.directiveRef;
index = this.componentRef.directiveRef.getIndex();
}
if (index < this.slides.length - 1) {
ref.setIndex(index + 1);
}
}
Я разветвил ваш проект с помощью решения stackblitz.
Ответ:
//inside component
@ViewChild(SwiperComponent) componentRefer: SwiperComponent;
//declare a variable to save index
var currentIndex = 0;
public onIndexChange(index: number) {
this.currentIndex = index;
}
swipeToNextSlideManually() {
if (this.currentIndex != 0) {
let indx = this.currentIndex + 1;
this.componentRefer.directiveRef.setIndex(indx);
}
}
А внутри html:
<swiper [config]="config " (indexChange)="onIndexChange($event) ">
<!--Btn click-->
<button (click)="swipeToNextSlideManually()">Next</button>