깜놀하는 해므찌로

Angular Swiper 활용 예시 본문

IT

Angular Swiper 활용 예시

agnusdei1207 2023. 6. 2. 23:01
반응형
SMALL
import { CommonModule } from '@angular/common';
import {
  AfterViewInit,
  CUSTOM_ELEMENTS_SCHEMA,
  Component,
  ElementRef,
  OnInit,
  ViewChild,
  Input,
} from '@angular/core';
import Swiper, { SwiperOptions } from 'swiper';
import { IconComponent } from '../../../components/icon/icon.component';
import { ScrollAnimationDirective } from '../../../animations/scroll-animation/scroll-animation.directive';

@Component({
  selector: 'index1-section',
  templateUrl: './index1.section.html',
  styleUrls: ['./index1.section.scss'],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  standalone: true,
  imports: [CommonModule, IconComponent, ScrollAnimationDirective],
})
export class Index1Section implements OnInit {
  @Input() visibleIndex!: number;
  @ViewChild('time') time: ElementRef<HTMLDivElement> | undefined;
  current: number = 0;
  swiper!: Swiper;
  timeLeft = 0;
  isSwiperRunning: boolean = true;

  constructor() {}

  ngOnInit() {
    this.setSwiper();
  }

  setSwiper() {
    const swiperEl = document.querySelector('.index1') as any;

    const options: SwiperOptions = {
      effect: 'fade',
      speed: 1400,
      autoplay: {
        delay: 5000,
        disableOnInteraction: false,
      },
      allowTouchMove: false,
      loop: true,
      touchRatio: 0,
      on: {
        autoplayTimeLeft: (swiper, timeLeft, percentage) => {
          this.timeLeft = 100 - Math.round(percentage * 100);
          if (this.time) {
            this.time.nativeElement.style.width = `${this.timeLeft}%`;
          }
          this.current = swiper.realIndex + 1;
        },
      },
    };

    this.swiper = new Swiper(swiperEl, options);
  }

  setSlide(slide: number): void {
    this.swiper.slideTo(slide - 1);
    this.current = slide - 1;
    this.swiper.slideReset();
  }

  toggleAutoplay(): void {
    if (this.swiper.autoplay.running) {
      this.isSwiperRunning = false;
      this.swiper.autoplay.running = false;
      this.swiper.autoplay.paused = true;
    } else {
      this.isSwiperRunning = true;
      this.swiper.autoplay.running = true;
      this.swiper.autoplay.paused = false;
      this.swiper.autoplay.resume();
    }
  }
}
반응형
LIST