2017-03-04 114 views
2

我是Angular 2的新手,我正在寻找一种方法来为移动用户实现一个良好的标签触摸滑动导航,并向下滑动切换到下一个标签视图。在Angular 2中实施滑动导航的最佳方式是什么?

到目前为止,我发现了一个名为angular2-useful-swiper的程序包,尽管我并不热衷于使用它,因为即使它们不在视图中,我也会尽早初始化组件。

有谁知道一个很好的方式来实现基于Swipe的导航Angular 2吗?任何反馈将不胜感激。 :)

回答

1

您可以使用HammerJS来实现触摸操作,例如,您可以按照此plunker

包括hammer.js文件

<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script> 

npm install hammerjs --save 

对于hammerjs浏览器支持触控,包括

<script src="http://cdn.rawgit.com/hammerjs/touchemulator/master/touch-emulator.js"></script> 
<script> 

进出口ORT在app.module.ts

import { HammerGestureConfig, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser'; 

export class MyHammerConfig extends HammerGestureConfig { 
    overrides = <any>{ 
    'swipe': {velocity: 0.4, threshold: 20} // override default settings 
    } 
} 

@NgModule({ 
    imports: [BrowserModule], 
    declarations: [AppComponent], 
    bootstrap: [AppComponent], 
    providers: [{ 
    provide: HAMMER_GESTURE_CONFIG, 
    useClass: MyHammerConfig 
    }] // use our custom hammerjs config 
}) 

plunker link for example

要实现标签angular2-material是一个良好的开端,遵循this link

+0

感谢您的支持! :) – Jonathan002

+0

感谢你,你可以请指导我如何平滑地移动我的页面像https://app.ft.com/index_page/home使用hammerjs – kamalav

+0

我在滑动时做导航。但是,如果我导航到一页面,其工作只有在重新加载后重新加载页面。我可以修复这个 – kamalav

17

对于刷卡检测这里是一个比增加HammerJS简单的解决方案:

在app.component.html:

<div (touchstart)="swipe($event, 'start')" (touchend)="swipe($event, 'end')"> 
    App content here 
</div> 

在app.component.ts:

private swipeCoord?: [number, number]; 
private swipeTime?: number; 

swipe(e: TouchEvent, when: string): void { 
    const coord: [number, number] = [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; 
    const time = new Date().getTime(); 

    if (when === 'start') { 
    this.swipeCoord = coord; 
    this.swipeTime = time; 
    } 

    else if (when === 'end') { 
    const direction = [coord[0] - this.swipeCoord[0], coord[1] - this.swipeCoord[1]]; 
    const duration = time - this.swipeTime; 

    if (duration < 1000 //Rapid 
     && Math.abs(direction[0]) > 30) //Long enough 
     && Math.abs(direction[0]) > Math.abs(direction[1] * 3) { //Horizontal enough 
    const swipe = direction[0] < 0 ? 'next' : 'previous'; 
    //Do whatever you want with swipe 
    } 
} 

注:我试过HammerJS解决方案,但将其配置为忽略鼠标手势是不可能的,因为你没有哈默对象的直接访问。所以选择一些文本是强制导航到下一页...

+3

这是怪胎真棒!谢谢 – dockleryxk

+1

这真的很棒。感谢分享!对我来说,它不够水平。我决定修改水平条件(Math.abs(direction [1] * 3)

+1

好主意@PierreChavaroche我相应地修改了代码! – pikiou

相关问题