2017-01-02 184 views
0

我有一个angular2应用程序,它有一个标题,内容在iframe中。我禁用CSS文件内的窗口滚动条:html {overflow-y:hidden;},我的目标是通过动画实现粘贴标题。带滚动条的iframe =不引发滚动事件(angular2)

我尝试了一些选项,但在我看来他们都不fireing /听iframe的滚动事件(窗口或doscument滚动事件没有问题fireing,但我并不需要它):

选项1(当我尝试,而不是(滚动(负载)),它的工作原理):

<iframe src=".." scrolling="yes" (scroll)="iframeScrollHandler(event)">..</iframe> 

选项2:

@ViewChild('iframe') iframe: ElementRef; 
constructor(@Inject(DOCUMENT) private document: Document, private window: Window, private renderer:Renderer) { 
    } 

    ngAfterViewInit(){ 
    this.renderer.listen(this.iframe.nativeElement, 'scroll', (event) => { 
     console.log('scroll scroll..'); 
    }) 

    } 

你知道为什么滚动事件不fireing?

回答

1

您可能已经找到了解决方案,但我最近发现了这个问题,最近发现这个问题没有答案。 关键似乎是您注册事件通知时的时间。在iframe的onload事件触发后,您必须注册滚动事件。在我的代码中,我在模板代码中注册了iframe的onload事件。

<form ngNoForm action="/logout" method="post" role="form"> 
    <div class="container-fluid main"> 
     <iframe #tframe [src]="src" class="frame" (load)="onFrameLoad()"> </iframe> 
     <div class="clearfix"> 
      <div class="pull-right"> 
       <button type="submit" class="btn btn-dialog-secondary">{{'common.decline' | i18n}}</button> 
       <button type="button" [disabled]="!scrollBottom" id="defaultFocus" class="btn btn-primary" (click)="accept()">{{'common.accept' | i18n}}</button> 
      </div> 
     </div> 
    </div> 
</form> 

在类本身我的iframe ElementRef成员(如藏汉,我想响应滚动事件更新, 后来更多在这个答案的布尔成员..)。

export class RouteFrame implements AfterViewInit { 
    scrollBottom: boolean = false; 
    @ViewChild('tframe') frame : ElementRef; 

    scroll$: any = null; 

}在RouteFrame类寄存器滚动事件的onFrameLoad()方法

然后。

onFrameLoad() { 

    this.scroll$ = Observable.fromEvent(this.frame.nativeElement.contentWindow, 'scroll') 
     .debounceTime(200) 
     .subscribe((evt: any) => { 
      this.onScroll(); 
     }); 
} 

然后在onScroll()方法中,执行所需的任何逻辑。在我看来,当用户滚动到iframe的底部。 但是我发现滚动事件正在Angular的“外部”发生,所以表单由Angular对该变量值的变化进行了重新评估,因此即使它的 有[禁用] =“!scrollBottom”作为其声明的一部分。因此,为什么scrollBottom变量的更新被封装在this.zone.run()中。

onScroll() { 

    if (this.frame.nativeElement.contentWindow.scrollY > this.frame.nativeElement.contentWindow.innerHeight) { 
     this.zone.run(() => { 
      this.scrollBottom = true; 
     }); 
    } 
} 

this.zone只是像其他Angular提供程序一样注入到RouteFrame类的cstr中。

constructor(@Inject(NgZone) private zone: NgZone, ....) 

为了完整性,在组件完成时取消订阅滚动事件侦听器。

NgOnDestroy() { 
    this.scroll$.unsubscribe(); 
} 

角版本4.3.0