Skip to content

How to access the host component from a directive ? #8277

Closed

Description

@frankpepermans

According to the change log (https://github.com/angular/angular/blob/master/CHANGELOG.md),
AppViewManager is renamed into ViewUtils and is a mere private utility service.

However, I was using AppViewManager.getComponent to obtain a Component reference from an ElementRef before, how would I do this now?

What I need to achieve is the following:

  • I have a Component with a selector (say: selector my-component)
  • A directive that can be placed upon Components (my-directive)

In HTML, it looks as following
<my-component my-directive></my-component>

From my-directive, I need to have a reference to the my-component Component instance.

If there is another (better) way of doing this, I'm happy to adapt my code

Activity

  1. tbosch commented on Apr 27, 2016

    @tbosch
    Contributor

    You could just inject that component into the directive.

    On Wed, Apr 27, 2016 at 4:34 AM Frank Pepermans [email protected]
    wrote:

    According to the change log (
    https://github.com/angular/angular/blob/master/CHANGELOG.md),
    AppViewManager is renamed into ViewUtils and is a mere private utility
    service.

    However, I was using AppViewManager.getComponent to obtain a Component
    reference from an ElementRef before, how would I do this now?

    What I need to achieve is the following:

    • I have a Component with a selector (say: selector my-component)
    • A directive that can be placed upon Components (my-directive)

    In HTML, it looks as following

    From my-directive, I need to have a reference to the my-component
    Component instance.

    If there is another (better) way of doing this, I'm happy to adapt my code

    —
    You are receiving this because you are subscribed to this thread.
    Reply to this email directly or view it on GitHub
    #8277

  2. frankpepermans commented on Apr 27, 2016

    @frankpepermans
    Author

    How would that work?

    The component could be anything really, or should in that case the component resolve a provider with its own instance as value, so that the directive can inject it dynamically?

  3. zoechi commented on Apr 27, 2016

    @zoechi
    Contributor

    @tbosch I think that would only work when the type is statically known by the directive but if the directive is added to different components, how would one inject it?

  4. frankpepermans commented on Apr 28, 2016

    @frankpepermans
    Author

    @tbosch can you comment an alternative? If getting a component from an ElementRef will be dropped, let me know so I can start reworking my solution.

  5. bennylut commented on Apr 30, 2016

    @bennylut

    Any workaround yet? I have a directive that assumes that the host component will have some specific interface. Without this feature (or some workaround) I will have to develop this directive for each component that implements this interface (which is what I will do if no other option)..

  6. CaptainCodeman commented on Apr 30, 2016

    @CaptainCodeman

    If the component has to be static, doesn't it kind of defeat the whole point of directives - why wouldn't you just move whatever the directive does right into the known component?

  7. bennylut commented on Apr 30, 2016

    @bennylut

    @CaptainCodeman, The idea was that instead of repeating the implementation of the same functionality in every component that follows a specific interface, I would have a directive that add this functionality.

    Here is a simplified example:
    Say I have a selection-info component that is just a simple panel that display information about some selected data.
    Now I have three components: list-view, tree-view and combo-box, each of these components has the following properties: selection:T, selectionChange:EventEmitter and valueToString: (T)=>string,
    in the previous version I could write a simple directive track-selection that receive an instance of selection-info as input, and take care of binding all the needed properties and even supply some additional services for debugging. In the new version it of course still possible but in a less elegant way in my eyes.

    This is of course a relatively simplified scenario but I hope it will be able to show the rational behind receiving the component in a directive without actually knowing it exact class but only it interface.

  8. CaptainCodeman commented on Apr 30, 2016

    @CaptainCodeman

    Yes, that is what a directive is supposed to do - add behavior to whatever component it's attached to.

    If that can no longer be done then it makes them kind of pointless - the behavior could be moved to a class that is pulled into each component instead (if things have to be statically defined).

  9. bennylut commented on Apr 30, 2016

    @bennylut

    @CaptainCodeman right, for now this is what I will do. But I hope that the angular team will provide an alternative as the directive approach was much more elegant..

  10. frankpepermans commented on Apr 30, 2016

    @frankpepermans
    Author

    This is exactly what I've been using directives for, a way to elegantly allow composition and enhance components.

    In my case state management, the component must implement a certain interface, the directive asserts that the component indeed implements it and then does its thing.

    I do hope this will still be possible :)

  11. dqweek commented on May 2, 2016

    @dqweek

    I have same issue described.
    I have found a dirty workaround, till official fix will be provided.

    This code works for me:

    @Directive({
        selector: 'foo'
    })
    class FooDirective
    {
       constructor(private _view: ViewContainerRef) {
      }
      ngOnInit() {
          let component = (<any>this._view)._element.component
    
         //TODO: add initialization code here
     }
    }
    

    explanation:
    AppElement initialized with component instance on compilation.
    AppElement is private to angular, so we can't DI it.
    Fortunately ViewContainerRef has a reference to it on initialization (it is private).

    it is a short run fix, till angular team provide better solution.

  12. zoechi commented on May 2, 2016

    @zoechi
    Contributor

    This doesn't work for Dart though because in Dart access to private members is effectively prevented.

  13. syndicatedshannon commented on May 24, 2016

    @syndicatedshannon

    We attempted to use this today, but as part of a workaround for a workaround for another need. The use-case may still be relevant, so I'll describe it briefly.

    Our hierarchical tree needs to Observe the result of a late-determined function, displaying resulting children. However, an Angular 2 function in a view, even one returning an Observable piped to async, never settles. To work-around, we passed a function reference from the view instead, which also required the view-containing component's context.

  14. giancarloa commented on Jun 16, 2016

    @giancarloa

    anyone know if a supported solution to this problem is available now? I too have a similar requirement... I have a child component that can literally be used inside of any type of parent component... and the child component needs to access the parent component...

  15. 114 remaining items

  16. swseverance commented on Oct 13, 2021

    @swseverance
    Contributor

    I could not get some of these approaches to work, and others seemed too hacky. So... I turned my directive into a "shell" component and used a ContentChild ref. Yes, you do need to know the type of component you need to reference in advance.

    @Component({
      selector: 'my-component',
      template: '<ng-content></ng-content>'
    })
    export class MyComponentThatWasOriginallySupposedToBeADirective implements AfterContentInit {
      @ContentChild(MyComponentINeedToReference) comp: MyComponentINeedToReference;
    
      ngAfterContentInit(): void {
        // use this.comp
      }
    }
    <my-component>
      <component-that-i-need-to-reference></component-that-i-need-to-reference>
    </my-component>
  17. LickIt commented on Oct 28, 2021

    @LickIt

    What about structural directives? Is there an easier way to get the component from the EmbeddedViewRef?

  18. MQpeng commented on Dec 1, 2021

    @MQpeng

    try this

    @Directive({
      selector: '[shortcut-form]',
    })
    export class ShortcutFormDirective implements OnInit, AfterViewInit {
      hostComponent:any;
      constructor(public el: ElementRef, private view: ViewContainerRef) {}
    
      ngOnInit(): void{
      }
    
      ngAfterViewInit(): void{
        this.hostComponent = this.view.injector.get(NzSelectComponent, null) || this.view.injector.get(CoSelectComponent, this.el.nativeElement);
      }
    }
    
  19. kayahr commented on Jan 13, 2022

    @kayahr

    With current Angular 13 this workaround with template ref and Input property no longer works:

    <app-sidebar #appSidebarRef  debounceEvent [componentRef]="appSidebarRef " ... >
    

    The input property is now undefined. Other input properties which reference other components are working so looks like Angular 13 only broke this self-reference.

    I had to downgrade to Angular 12 to get it working again... Does someone know a workaround which doesn't hack into private properties and which works with Angular 13?

  20. amninderchahal commented on Jan 13, 2022

    @amninderchahal

    @kayahr Seems to be working in angular 13.1.2. Are you sure your property name is correct.

  21. kayahr commented on Jan 14, 2022

    @kayahr

    @kayahr Seems to be working in angular 13.1.2. Are you sure your property name is correct.

    Huh, strange... Yes, the property name is correct. Without changing the code it works with Angular 12 but not with 13. At what time do you access the property in your code? I tried on init and on after-view-init, in both cases the property is undefined with Angular 13.

    Or maybe there is a difference if angular-cli is used to compile the beast and Angular 13 now has even more black magic which forces me into accepting their compiler? I don't use that, my project is a standard TypeScript environment.

  22. amninderchahal commented on Jan 16, 2022

    @amninderchahal

    @kayahr I can access component ref in both on-init and after-view-init hooks. I did try it in a new project in v13 just for testing this. Not sure why it won't work in your application if it's a typical application.

    Also I think if the component/directive has exportAs option used to name it then you have to use the name specified for that option to grab the reference.

  23. AndrewKushnir commented on Jan 21, 2022

    @AndrewKushnir
    Contributor

    We've discussed this feature request as a part of the Feature Request process.

    There are few solutions mentioned in this thread:

    • using DI to inject a host component instance reference (when the component class is known)
    • declaring a provider on a host component (with a reference to the component itself) and injecting that token into a directive (when there are different types of components that should be handled by a directive)
    • using a local ref to a component and pass that as an input to a directive

    Those solutions provide a way to access a host element in an explicit and type-safe way, so we encourage using one of those options.

    We are closing this ticket, please create a new one if there are some use-cases that can not be covered by one of the options mentioned above (and described in this thread).

  24. platon-rov commented on Feb 11, 2022

    @platon-rov

    declaring a provider on a host component (with a reference to the component itself) and injecting that token into a directive (when there are different types of components that should be handled by a directive)

    it won't work for structural directives btw, is it intended? Once you turn it into attribute directive it works.

  25. Totati commented on Feb 11, 2022

    @Totati
    Contributor

    it won't work for structural directives btw, is it intended? Once you turn it into attribute directive it works.

    Yes, <my-comp *ngIf="true"> is a syntactic sugar for <ng-template [ngIf]="true"><my-comp>.... As you can see the component is not the host.

  26. Nanges commented on Feb 22, 2022

    @Nanges

    @tbosch I think that would only work when the type is statically known by the directive but if the directive is added to different components, how would one inject it?

    To prevent this, I use a third party directive that actes as proxy and provides a common interface.

    e.g:

    app.component.html

    <kendo-dropdownlist appMyDataProvider></kendo-dropdownlist>

    The common interface used by directives that will handle the dropdown (or another kind of component)

    export interface DataComponentAccessor {
        populate(data: any[]);
    }
    
    export const DATA_COMPONENT_ACCESSOR = new InjectionToken('Data component accessor');

    The proxy. Only this guy knows how work the third party component.

    The selector is the same as kendo-dropdownlist to make implementation more friendly.

    @Directive({
        selector: 'kendo-dropdownlist',
        providers: [
            {
                provide: DATA_COMPONENT_ACCESSOR,
                useExisting: forwardRef(() => DropDownListAccessorDirective),
            },
        ],
    })
    export class DropDownListAccessorDirective implements DataComponentAccessor {
        constructor(private component: DropDownListComponent) {}
    
        populate(data: any[]) {
            this.component.data = data;
        }
    }

    The data provider. As you can see, there is no reference to the kendo-component.

    @Directive({
        selector: '[appMyDataProvider]',
    })
    export class MyDataProviderDirective implements OnInit {
        constructor(@Inject(DATA_COMPONENT_ACCESSOR) private component: DataComponentAccessor) {}
    
        ngOnInit(): void {
            this.component.populate(['foo', 'bar', 'baz']);
        }
    }
  27. Lonli-Lokli commented on Feb 22, 2022

    @Lonli-Lokli

    @Nanges there is no strict types here so it becomes useless

  28. angular-automatic-lock-bot commented on Mar 25, 2022

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  29. locked and limited conversation to collaborators on Mar 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: corecore: difeaturefeature: under consideration

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions