Angular无法检测到滑动滑块变化

时间:2019-05-11 08:37:22

标签: angular onchange swiper ngonchanges

我正在使用swiper library。在上方链接的API中,您可以找到mySwiper.activeIndex返回了当前选择的幻灯片。我想做的就是每当更改幻灯片时都更新我的服务,以便我的应用程序知道其他部分(通过共享服务)选择了哪个幻灯片。

所以我想使用的是ngOnChanges,它想检测组件中的每一个变化,但是由于我的代码console.log没什么,它不能检测到滑模变化。代码:

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);
    }
}

在此代码中,setTimeout可以正常工作,并在加载应用程序4秒钟后向我显示当前选择的幻灯片。但是这个ngOnChanges(changes) {似乎从未被解雇,因为我看不到任何console.logs。

为什么ngOnChanges无法捕获mySwiper的更改?我该怎么做才能发现这种变化?

1 个答案:

答案 0 :(得分:0)

有两个原因无法解决问题:

首先,ngOnChanges()仅在组件的绑定属性之一已更改时才会触发,例如@Input变量。

ngOnChanges

  

在默认更改后立即调用的回调方法   检测器已检查数据绑定属性,如果至少一项已更改

第二,即使Swiper是输入属性,对Swiper对象的更改也不会导致更改检测触发,请参见my other answer;仅对数据绑定对象属性的引用更改。

解决方案

在touchEnd事件发生时运行“更改”代码:

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