组件渲染后如何从指令中调用函数? [英] How can I call function from directive after component's rendering?

查看:90
本文介绍了组件渲染后如何从指令中调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有组件:

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

我想调用此函数:

export class Directive {

functionFromDirective() {
//something hapenns
}

我该怎么做?

推荐答案

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

You can retrieve Directive from Component's template with ViewChild like this:

@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()
  }
}

这篇关于组件渲染后如何从指令中调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆