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

随声附和 提交于 2019-12-10 17:09:25

问题


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?


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



回答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.



来源:https://stackoverflow.com/questions/40549894/how-can-i-call-function-from-directive-after-components-rendering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!