What is the best way to implement swipe navigation in Angular 2?

后端 未结 4 1553
[愿得一人]
[愿得一人] 2020-12-12 23:24

I\'m new to Angular 2 and am looking for a way to implement a good tab touch swipe navigation for mobile users with a swipe transition to the next tab view.

So far I

4条回答
  •  死守一世寂寞
    2020-12-13 00:13

    I managed to come up with a write-once-use-everywhere type of function which I put in a dir called "gestures" and then created a file called "swipe.ts" and put this inside.

    let swipeCoord = [0, 0];
    let swipeTime = new Date().getTime();
    
    export function swipe(e: TouchEvent, when: string): void {
    
        const coord: [number, number] = [e.changedTouches[0].clientX, e.changedTouches[0].clientY];
        const time = new Date().getTime();
    
        if (when === 'start') {
            swipeCoord = coord;
            swipeTime = time;
        } else if (when === 'end') {
            const direction = [coord[0] - swipeCoord[0], coord[1] - swipeCoord[1]];
            const duration = time - swipeTime;
    
            if (duration < 1000 //
                && Math.abs(direction[0]) > 30 // Long enough
                && Math.abs(direction[0]) > Math.abs(direction[1] * 3)) { // Horizontal enough
                const swipeDir = direction[0] < 0 ? 'next' : 'previous';
                if (swipeDir === 'next') {
                    alert('swipe next');
                } else {
                    alert('swipe prev');
                }
            }
        }
    }
    

    Then import into the desired component, like so:

    import {swipe} from '../../gestures/swipe';
    

    And create a function called:

    onSwipe(e: TouchEvent, when: string) {
            swipe(e, when);
        }
    

    In the HTML of the desired component, go with this:

        

    PS - credit goes to @pikiou. I just came up with a higher level of abstraction, which to me makes a lot more sense.

提交回复
热议问题