How to access the Component on a Angular2 Directive?

前端 未结 5 752
無奈伤痛
無奈伤痛 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:44

    UPDATE:

    Since Beta 16 there is no official way to get the same behavior. There is an unofficial workaround here: https://github.com/angular/angular/issues/8277#issuecomment-216206046


    Thanks @Eric Martinez, your pointers were crucial in getting me in the right direction!

    So, taking Eric's approach, I have managed to do the following:

    HTML

    
    
    
    
    
    

    Three different components, all of the share the same layout-item attribute.

    Directive

    @Directive({
      selector : '[layout-item]'
    })
    export class MyDirective {
      constructor(private _element: ElementRef, private _viewManager: AppViewManager) {
        let hostComponent = this._viewManager.getComponent(this._element);
        // on hostComponent we have our component! (my-component, my-second-component, my-third-component, ... and so on!
      }
    
    }
    

提交回复
热议问题