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

后端 未结 2 1906
闹比i
闹比i 2021-01-19 05:25

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

I have component:

export class Component {
  ngAfterContentInit() {
  // How c         


        
相关标签:
2条回答
  • 2021-01-19 06:19

    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.

    0 讨论(0)
  • 2021-01-19 06:22

    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()
      }
    }
    
    0 讨论(0)
提交回复
热议问题