How to detect a click on a slide in Swiper?

11,294

this is in the wrong context. In the documentation it says:

Please note, that this keyword within event handler always points to Swiper instance

Try without mySwiper, only this.clickedSlide.

Share:
11,294
chick3n0x07CC
Author by

chick3n0x07CC

Updated on June 14, 2022

Comments

  • chick3n0x07CC
    chick3n0x07CC almost 2 years

    I have an Angular 2 component which contains a slider from the Swiper package. I want to know which slide (its index) I have clicked on. Trying to follow Swiper documentation I have this:

    import { Component, AfterViewInit } from "@angular/core";
    import Swiper from "swiper";
    
    @Component({
        selector: "challenges",
        templateUrl: "challenges.component.html"
    })
    export class ChallengesComponent implements AfterViewInit {
        public mySwiper: Swiper;
        public slides = [
            "https://via.placeholder.com/300x200/",
            "https://via.placeholder.com/300x200/",
            "https://via.placeholder.com/300x200/"
        ];
    
        constructor() { }
    
        public ngAfterViewInit() {
            this.mySwiper = new Swiper(".swiper-container", {
                slidesPerView: 3,
                spaceBetween: 30,
                pagination: {
                    el: ".swiper-pagination",
                    type: "bullets",
                    clickable: true
                },
                on: {
                    click: function(){
                        console.log(this.mySwiper.clickedSlide);
                    }
            }
            });
        }
    }
    

    The problem is that if I click on one slide, it gives me this error this.mySwiper is undefined. Why, if this.mySwiper is a class member?

  • chick3n0x07CC
    chick3n0x07CC almost 6 years
    Precisely for what the documentation says, I understand that we need this prefix in order to access swiper properties (like clickedSlide). In fact, without prefix, after testing it, it says mySwiper is undefined.
  • MichaelKie
    MichaelKie almost 6 years
    I got it mixed up, since this points to the Swiper Instance the mySwiper shouldn't be needed, I edited my answer can you try that way?