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

11,701

Solution 1

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()
  }
}

Solution 2

Calling the method from within a component is not a good idea. Using a directive helps in a modular design, but when you call the method, you get a dependency from the component to the directive.

Instead, the directive should implement the AfterViewInit interface:

@Directive({
    ...,
    selector: '[directive]',
})
export class DirectiveClass implements AfterViewInit {
    ngAfterViewInit(): void {}
}

This way, your component doesn't have to know anything about the directive.

Share:
11,701
John Doe
Author by

John Doe

Updated on June 06, 2022

Comments

  • John Doe
    John Doe almost 2 years

    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?

  • John Doe
    John Doe over 7 years
    Thanks a lot! You really helps me.
  • Akber Iqbal
    Akber Iqbal almost 6 years
    in the sequence of events, the Directive's AfterViewInit ran earlier than my Component's ngAfterContentChecked... but it depends upon a person's requirement