swiper.service.ts
import { ElementRef, Injectable } from '@angular/core';
import { SwiperOptions } from 'swiper';
import { SwiperContainer } from 'swiper/element';
@Injectable({
providedIn: 'root',
})
export class SwiperService {
initSwiper(ref: ElementRef<SwiperContainer>, slidesPerView: number, breakpoints?: SwiperOptions['breakpoints']): void {
const options: SwiperOptions = {
slidesPerView: slidesPerView,
spaceBetween: 10,
centeredSlides: false,
loop: false,
autoplay: false,
navigation: {
nextEl: '.icon-chevron-right',
prevEl: '.icon-chevron-left',
},
breakpoints: breakpoints,
};
const swiperEl = ref.nativeElement;
Object.assign(swiperEl, options);
swiperEl.initialize();
}
}
swiper.component.ts
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import { SwiperContainer, register } from 'swiper/element/bundle';
import { SwiperService } from '../../services/swiper.service';
@Component({
selector: 'app-swiper',
templateUrl: './swiper.component.html',
styleUrls: ['./swiper.component.scss'],
})
export class SwiperComponent implements AfterViewInit {
constructor(private readonly swiperService: SwiperService) {
register();
}
// Swiper start
@ViewChild('swiperRef', { static: true })
protected _swiperRef: ElementRef<SwiperContainer>;
ngAfterViewInit(): void {
this.swiperService.initSwiper(this._swiperRef, 9, {
320: {
slidesPerView: 1,
spaceBetween: 20,
},
640: {
slidesPerView: 2,
},
768: {
slidesPerView: 3,
},
1024: {
slidesPerView: 4,
},
});
}
// Swiper end
}