How can I call function from directive after component's rendering?

Max K picture Max K · Nov 11, 2016 · Viewed 10.6k times · Source

How can I call function from directive after component's rendering?

I have component:

export class Component {
  ngAfterContentInit() {
  // How can i call functionFromDirective()?
  }
}

And I want call this function:

export class Directive {

functionFromDirective() {
//something hapenns
}

How can i do this?

Answer

Yaroslav Grishajev picture Yaroslav Grishajev · Nov 11, 2016

You can retrieve Directive from Component's template with ViewChild like this:

@Directive({
  ...,
  selector: '[directive]',
})
export class DirectiveClass {
  method() {}
}

In your component:

import { Component, ViewChild } from '@angular/core'
import { DirectiveClass } from './path-to-directive'

@Component({
  ...,
  template: '<node directive></node>'
})
export class ComponentClass {
  @ViewChild(DirectiveClass) directive = null

  ngAfterContentInit() {
    // How can i call functionFromDirective()?
    this.directive.method()
  }
}