How to access the Component on a Angular2 Directive?

前端 未结 5 684
無奈伤痛
無奈伤痛 2020-12-23 22:48

I\'m doing some tests with Angular 2 and I have a directive (layout-item) that can be applied to all my components.

Inside that directive I want to be able to read s

5条回答
  •  一生所求
    2020-12-23 23:26

    This solution was linked to in the comments of one of the other answers but it was hidden at the end of quite a long discussion so I will add it here.

    Import ViewContainerRef and inject it into your directive.

    import { ViewContainerRef } from '@angular/core';
    ...
    constructor(private viewContainerRef: ViewContainerRef) {}
    

    You can then access the following private/unsupported property path to retrieve the component instance which is associated with the element that has been decorated with the directive.

    this.viewContainerRef._data.componentView.component
    

提交回复
热议问题