如何从指令中获取角度视图层次结构? [英] How can I get the angular view hierarchy from a directive?

查看:66
本文介绍了如何从指令中获取角度视图层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular版本6 +

Angular version 6+

我正在研究一个指令,可以将其放置在任何元素上以用于常规用法日志记录.对于上下文,它看起来类似于以下内容:

I'm working on a directive that can be placed on any element for the purposes of general usage logging. For context, it would look something like the following:

@Directive({
  selector: '[log]'
})
export class LogDirective {
  @Input() log: string; // the log message
  @Input() logOn: string; // event name to trigger logging

  constructor(private renderer: Renderer2,
              private elementRef: ElementRef) {
  }

  ngOnInit() {
    this.renderer.listen(this.elementRef.nativeElement, this.logOn, () => {
      // log the message, etc.
    }
  }
}


<div log="Clicked the element" logOn="click">Click Me</div>


这很好用,但是我认为自动获取某种类型的父级层次结构可以进行记录会很酷.这样,某人可以查看日志,并很容易看到它的记录位置.类似于"AppComponent-> SomeOtherComponent-> ParentCompnent".有什么可以注入到该指令中的东西,可以确定它在视图层次结构中的位置吗?


This works fine, but I thought it would be cool to automatically get some type of parent hierarchy so that could be logged. That way someone could look at the log and see pretty easily where this was logged from. Something like "AppComponent -> SomeOtherComponent -> ParentCompnent". Is there something that can be injected to this directive that could determine where it lives in the view hierarchy?

推荐答案

,您可以将ViewContainerRef注入指令以访问托管组件. 然后,您可以使用它来读取当前组件和该组件的父组件.

you can inject ViewContainerRef to the directive to get access to hosting component. you can then use that to both read the current component and the parent component of that component.

如此递归将为您带来想要的结果.

doing so recursively will get you the result you're after.

类似这样的东西(我将递归算法留给您):

something like this (i'll leave the recursion algorithm to you):

constructor(private viewContainerRef: ViewContainerRef) { }

private clicked() {
    console.log(this.viewContainerRef['_view'].component);
    console.log(this.viewContainerRef['_view'].parent.component);
    console.log(this.viewContainerRef['_view'].parent.parent.component);
  }

(1)Stackblitz演示

(1)忽略该应用程序的其余部分,我在Google上搜索了某人的"Angular指令模板",并对其进行了更改以使其快速获取

(2)当然,免责声明:您不应该在角度上阅读_attributes,因为它可以在将来的版本中进行更改而无需通知,并且您将不支持这些内容",等等..

(2)of course, disclaimer, "you shouldn't be reading _attributes on angular because it can be changed without notification in future versions and you'll have no support for those" etc, etc etc..

这篇关于如何从指令中获取角度视图层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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