Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call methods of component from directive in angular 2

Tags:

angular

this is my code directive:

import { Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appScrollToEnd]'
}) 
export class ScrollToEndDirective {
  constructor(private element: ElementRef) { }
  @HostListener('scroll') onScroll(){
    console.log(this.element
  } 
}

and in my view template

<div class="content" appScrollToEnd="functionInComponent($event)"></div>

How can i call methods functionInComponent() when scroll. i know angular2 can listen event scroll, but my purpose is call method of component from directive. Thank

like image 846
nguyen anhtuan Avatar asked Oct 02 '17 14:10

nguyen anhtuan


1 Answers

You can have a @Output event in your directive, and bind the same wherever you are using it to some component method,

@Directive({
  selector: '[appScrollToEnd]'
}) 
export class ScrollToEndDirective {
  @Output() appScrollToEnd = new EventEmitter();

  constructor(private element: ElementRef) { }

  @HostListener('scroll') onScroll(){
    this.appScrollToEnd.emit('someValue');
  } 
}


@Component({
  selector: 'my-app',
  template: `
    <div class="content" (appScrollToEnd)="functionInComponent($event)">
      <div class="text">Some text</div> 
    </div>
  `,
})
export class App {
  functionInComponent(e) {
    console.log(e):
  }
}

Thanks @yurzui for the Plunker sample.

Here is the Plunker!!

like image 64
Madhu Ranjan Avatar answered Oct 13 '22 02:10

Madhu Ranjan