Angular2, HostListener, how can I target an element? can I target based on class?

后端 未结 8 1156
后悔当初
后悔当初 2020-12-05 01:50

In Angular2, how can I target an element within the HostListener decorator?

@HostListener(\'dragstart\', [\'$event\'])
    onDragStart(ev:Event) {
        co         


        
8条回答
  •  不知归路
    2020-12-05 02:41

    As pointed out by Googs, the accepted answer does answer the question but doesn't help find a solution.

    I built upon alex's answer as I needed a way to use the functionality I already had in my @HostListener for retrieving a list of notifications for different screen sizes.

    For example, in my app - the notifications page has its own route on mobile but existed in the sidebar on tablet and screen sizes above, so I couldn't use the @HostListener there as it would only trigger when I hit the bottom of the whole page and not the sidebar.

    Instead I looked up the

    I was interested in and attached what I needed. So the following code:

    attachListenerToContainer() {
        let elementToListenTo = this.ele ? this.ele : 'window';
    
        this.renderer.listen(elementToListenTo, 'scroll', (event) => {
          if(!this.reachedBottom) {
            if((getHeight(this.ele) + getScrollTop(this.ele)) >= getOffset(this.ele)) {
              this.reachedBottom = true;
              this.getNextNotificationsPage();
            }
          }
        });
    
        function getScrollTop(ele) {
          return ele ? ele.scrollTop : window.scrollY;
        }
        function getHeight(ele) {
          return ele ? ele.clientHeight : window.innerHeight;
        }
        function getOffset(ele) {
          return ele ? ele.scrollHeight : document.body.offsetHeight;
        }
      }
    

    The this.ele is the container div I'm interested in which I look up in the ngAfterViewInit() lifecycle hook for tablet and above. If I can't find that element then I use the window instead - effectively emulating the @HostListener

    Also - here's how I was looking up, in my case, the container element I wanted:

    this.ele = document.getElementsByClassName('notifications')[0]; 
    

提交回复
热议问题