【问题标题】:How can I call function from directive after component's rendering?如何在组件渲染后从指令中调用函数?
【发布时间】:2017-03-25 19:07:47
【问题描述】:

如何在组件渲染后从指令中调用函数?

我有组件:

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

我想调用这个函数:

export class Directive {

functionFromDirective() {
//something hapenns
}

我该怎么做?

【问题讨论】:

    标签: angular typescript angular2-directives angular2-components


    【解决方案1】:

    您可以使用 ViewChild 从组件的模板中检索指令,如下所示:

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

    在您的组件中:

    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】:

    从组件中调用方法不是一个好主意。使用指令有助于模块化设计,但是当您调用方法时,您会获得从组件到指令的依赖关系。

    相反,指令应该实现 AfterViewInit 接口:

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

    这样,您的组件就不必了解指令的任何内容。

    【讨论】:

    • 在事件序列中,Directive 的 AfterViewInit 比我的 Component 的 ngAfterContentChecked 运行得更早...但这取决于个人的要求
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2022-01-16
    • 2018-05-04
    • 2019-11-22
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多