如何从指令访问主机组件?

编程入门 行业动态 更新时间:2024-10-25 02:28:55
本文介绍了如何从指令访问主机组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

假设我有以下标记:

<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/angular/angular/issues/8277
当您事先不知道类型时,它还提供了一些解决方法.

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

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

更多推荐

[db:关键词]

本文发布于:2023-04-22 11:54:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023527.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   组件   主机

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!