Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 684
Max K Avatar asked Dec 02 '22 12:12

Max K


2 Answers

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()
  }
}
like image 106
Yaroslav Grishajev Avatar answered Dec 05 '22 16:12

Yaroslav Grishajev


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.

like image 25
Heiner Lamprecht Avatar answered Dec 05 '22 18:12

Heiner Lamprecht