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

Posted

技术标签:

【中文标题】如何在组件渲染后从指令中调用函数?【英文标题】: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

我该怎么做?

【问题讨论】:

【参考方案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 运行得更早...但这取决于个人的要求

以上是关于如何在组件渲染后从指令中调用函数?的主要内容,如果未能解决你的问题,请参考以下文章

在 React 中,为啥子组件的渲染函数会被调用两次?

如何在 React 组件中每分钟调用一个函数?

即使调用了渲染函数中的 console.log,组件也不会在状态更改时重新渲染

如何在 React Native 中使用函数渲染组件

Vue.js 在渲染组件上调用函数

C# - 在一些计算后从另一个构造函数调用构造函数[重复]