如何从指令访问主机组件? [英] How to access host component from directive?

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

问题描述

说我有以下标记:

<my-comp myDirective></my-comp>

有什么方法可以从指令中访问组件实例 ?

Is there any way I can access the component instance from the directive?

更具体地说,我希望能够从MyDirective访问MyComponent的属性和方法,最好是不向上方的HTML添加任何内容.

More specifically I want to be able to access the properties and methods of MyComponent from MyDirective, ideally without adding anything to the HTML above.

推荐答案

您可以直接注入

class MyDirective {
  constructor(private host:MyComponent) {}

一个严重的限制是,您需要提前知道组件的类型.

A severe limitation is, that you need to know the type of the component in advance.

另请参见 https://github.com/angular/angular/issues/8277
当您事先不知道类型时,它还提供了一些解决方法.

See also https://github.com/angular/angular/issues/8277
It also provides some workarounds for when you don't know the type in advance.

这篇关于如何从指令访问主机组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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