Angular:在父组件上监听滚动事件?

时间:2018-12-11 15:13:35

标签: angular

假设我有2个组成部分:

父母的模板:

<div #scrollable style="overflow: scroll">
   <ng-content></ng-content>
</div>

用例:

 <parent>
     <child></child>
 </parent>

什么是在scroll组件内部侦听#scrollable div的<child></child>事件的“角度”分离方法?

AFAIK @HostListener无法定位#scrollable

谢谢

2 个答案:

答案 0 :(得分:2)

实现您的孩子将要实现的接口:

interface ScrollableParent {
  parentOnScroll(event: MouseScrollEvent);
}

然后在子选择器上使用模板变量来从父模板触发函数:

<parent (scroll)="child.parentOnScroll($event)">
  <child #child></child>
</parent>

答案 1 :(得分:1)

您实际上可以通过指令的HostListener

收听滚动事件

已经创建了一个Stackblitz Demo供您参考。检查控制台部分中的示例发出的控制台日志。

AppDirective

@Directive({
  selector: '[listenScroll]'
})
export class AppDirective {

  // This will emit the scroll update to whatever you want to assign with its emitted value
  @Output() windowScroll: EventEmitter<any> = new EventEmitter<any>();


  @HostListener("window:scroll", [])           // Listens to Window Scroll Event
  onWindowScroll() {
    this.windowScroll.next('scrolled');       // Use the @Output() windowScroll to emit a simple string 'scrolled' whenever the window triggers a scroll event from the user
  }

}

ParentComponent

 @Component({
  selector: 'my-app',
  template: `
     <div listenScroll                                     // Our directive attached to the element
          (windowScroll)="isScrolled$.next('scrolled')">   // Since the directive has been attached, we can also call and use its windowScroll @Output event emitted from the directive itself that we had created.

        <child [scrollUpdate]="isScrolled$"></child>   // Add an input [] scrollUpdate bracket to the ChildComponent to subscribe to whatever scroll event that its parent listens and passes to

     </div>
  `,
  styles: [`div { height: 200vh; }`]
})
export class AppComponent  { 

  isScrolled$: Subject<string> = new Subject<string>();     We use a RxJS Subject as it is a continuous event that we want to subscribe to dynamically

}

ChildComponent

@Component({
  selector: 'child',
  template: `<div>I am a child</div>`
})
export class ChildComponent implements OnInit {

  @Input() scrollUpdate: string;      // It stores here whatever the scroll event update that its parent has passed in to

  constructor() {}

  ngOnInit(): void {
    // Listens and Subscribes to the latest emitted value from @Input() which its value is dependent from the parent's directive scroll update 
    this.scrollUpdate.subscribe(val => console.log('Child: ', val));
  }

}
相关问题