0

I'm using swiper library. In API from above link you can find that mySwiper.activeIndex is returning currectly selected slide. What I want to do is update my service whenever slide is changed so my app will know which slide is selected in other parts (by sharing service).

So what I wanted to use is ngOnChanges which suppose to detect every change in component but it doesn't detect slide change because my code doesn't console.log anything. Code:

import { Component, OnInit, AfterViewInit, OnChanges } from '@angular/core';
import Swiper from 'swiper';
import {TouchService} from "../../services/touch.service";

@Component({
    selector: 'app-nav',
    templateUrl: './nav.component.html',
    styleUrls: [ './nav.component.scss' ]
})
export class NavComponent implements AfterViewInit, OnChanges, OnInit {
    mySwiper: Swiper;

    slides = [
        'Slide1',
        'Slide2',
        'Slide3',
        'Slide4',
        'Slide5',
        'Slide6'
    ];

    constructor(private touchService: TouchService) {}

    ngAfterViewInit() {
        this.mySwiper = new Swiper('.nav', {
            paginationClickable: false,
            grabCursor: true,
            loop: true,
            slidesPerView: 3,
            spaceBetween: 50
        });

        this.mySwiper.on('touchStart', () => {
            this.touchService.triggerTouchStart();
        });
        this.mySwiper.on('touchEnd', () => {
            this.touchService.triggerTouchStop();
        });
    }
    ngOnChanges(changes) {
        console.log(changes);
    }
    ngOnInit() {
        setTimeout(() => {
            alert(this.mySwiper.activeIndex);
        }, 4000);
    }
}

In this code setTimeout works correctly and show me currently selected slide after 4 seconds from app load. But this ngOnChanges(changes) { seems to be never fired because I don't see any console.logs.

Why ngOnChanges doesn't catch mySwiper changes? What can I do to detect such changes?

BT101
  • 3,666
  • 10
  • 41
  • 90

1 Answers1

0

There are two reasons this doesn't work:

Firstly, ngOnChanges() will only fire when one of the component's bound properties has changed, e.g. an @Input variable.

ngOnChanges:

A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed

Secondly, even if Swiper was an input property, mutations to the Swiper object would not cause change detection to fire, see my other answer; only a reference change to a data-bound object property will.

Solution

Run your 'changes' code when the touchEnd event occurs:

this.mySwiper.on('touchEnd', () => { this.touchService.triggerTouchStop(); // Your code here. });