81

Say I have the following markup:

<my-comp myDirective></my-comp>

Is there any way I can access the component instance from the directive?

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.

AngularChef
  • 13,797
  • 8
  • 53
  • 69

12 Answers12

95

You can just inject it

class MyDirective {
  constructor(private host:MyComponent) {}

A severe limitation is, that you need to know the type of the component in advance.

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thank you, Günter, it works. Ideally I would need a generic solution that works for any component. In fact you might have a suggestion for what I'm trying to do here: https://stackoverflow.com/questions/46014977 – AngularChef Sep 02 '17 at 14:51
  • 1
    A generic solution is requested by many (as you can see in the linked issue), but currently there is no easy solution for that. – Günter Zöchbauer Sep 02 '17 at 15:09
  • @GünterZöchbauer I presume we could use an interface e.g. `constructor(private host: HostedComponentInterface){}` and require that the user of the directive implements that interface?? – Drenai Dec 12 '17 at 11:13
  • TypeScript interfaces don't exist at runtime and are therefore not supported for DI. – Günter Zöchbauer Dec 12 '17 at 11:17
  • You might be looking for something like https://stackoverflow.com/questions/35971943/query-is-not-working-on-inherited-classes/35971968#35971968 – Günter Zöchbauer Dec 12 '17 at 11:57
  • My component never gets injected, are there any limitations not specified here? – Lovro Gregorčič Dec 13 '17 at 14:53
  • I don't know of any limitations. Try to create a minimal reproduction in http://stackblitz.com. – Günter Zöchbauer Dec 13 '17 at 14:54
  • angular has so many limitations like this but never a workaround/solution. There's such a lack of support with concepts that regard just accessing a component/directive without having to know the exact component ahead of time. – Emobe May 24 '19 at 14:20
  • 1
    @Emobe I haven't run into many situations where I couldn't find a solution. This was one of the hardest. For others there were usually good workarounds. Most design decisions were made for efficiency and I think it's worth it. – Günter Zöchbauer May 24 '19 at 15:50
  • I think the answer from Sunil Garg is a better one because this cannot be used in some general directive. – Loic Sep 23 '20 at 07:42
  • I am trying to use a simple base class `FormfieldDirective` which marked with `@Directive`, to reference my holding component (which inherits this class): constructor( @Host() @Self() private bcControl: FormfieldDirective ), but getting weird error: `Module not found`, even though the reference is correct... Any idea why? – Alexander Jul 11 '22 at 14:40
31

If you want to use the attribute directive on your custom components you could have those components extend from an abstract class and 'forwardRef' the abstract class type to your component type. This way you can make angular's DI select on the abstract class (within your directive).

Abstract class:

export abstract class MyReference { 
  // can be empty if you only want to use it as a reference for DI
}

Custom Component:

@Component({
  // ...
  providers: [
    {provide: MyReference, useExisting: forwardRef(() => MyCustomComponent)}
  ],
})
export class MyCustomComponent extends MyReference implements OnInit {
// ...
}

Directive:

@Directive({
  selector: '[appMyDirective]'
})
export class CustomDirective{

  constructor(private host:MyReference) {
    console.log(this.host);
    // no accessing private properties of viewContainerRef to see here... :-)
  }

}

This way you can use the directive on any component that extends your abstract class.

This will of course only work on your own components.

Michiel Windey
  • 343
  • 3
  • 4
  • This was what I needed for reference any component with my directive – Diego Fernando Murillo Valenci May 20 '20 at 18:27
  • Remember to make the abstract class injectable else you will get an error in your directive. For example, add `@Injectable({ providedIn: 'root'})` as an attribute to your abstract class – Alf Moh Jan 18 '21 at 12:15
  • 1
    Some notes: 1. It works! 2. The forwardRef is actually not necessary, at least with latest versions of Angular. 4. You can use the abstract class as an interface: `class MyCustomComponent extends AbstractCustomComponent implements MyReference, OnInit` 3. What Alf Moh says is not necessary… – PhiLho Oct 20 '21 at 08:14
  • This is actually genius – Christian Vincenzo Traina Jan 10 '23 at 20:49
  • @PhiLho, Please provide a full example because Michiel's solution works for me, but not yours. – ilcorvo Apr 17 '23 at 14:35
29

Your directive could be the generic one that can be applied to any of your components. So, in that case, injecting the component in constructor would not be possible, So here is one other way to do the same

Inject the ViewContainerRef in constructor

constructor(private _viewContainerRef: ViewContainerRef) { }

and then get it using

let hostComponent = this._viewContainerRef["_data"].componentView.component;
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
  • 8
    As of Angular 9.0.0-next.3, this solution doesn't work anymore. Do you have any clue where they might have hidden it now? – Fredrik_Borgstrom Aug 23 '19 at 09:30
  • 2
    @Fredrik_Macrobond _.last(this.viewContainerRef['_hostView'][0].__ngContext__) – Devin Garner May 14 '20 at 23:10
  • 1
    Anyone found a decent solution for Ivy? Angular10 – Stephen Lautier Oct 28 '20 at 19:25
  • 1
    A very dirty solution with Angular 12: `(this.viewContainerRef as any)._hostLView[8]`. 8 refers to CONTEXT (inlined) in https://github.com/angular/angular/blob/a92a89b0eb127a59d7e071502b5850e57618ec2d/packages/core/src/render3/interfaces/view.ts#L180 To use with caution. – ARno May 25 '21 at 14:37
  • 1
    The main issue with this solution is that it is an 'internal' solution and, as you can see in the previous comments, you will never be sure that the internal code is not changing from one version to another. So if you take this solution, you will have to review your code every time you are upgrading Angular. It's a good solution but it has a cost... – MatRt Feb 08 '22 at 11:56
21

This is taken from the github issue and works like a charm. The downside is needing to know the components beforehand, but in your case you would need to know the methods you're using anyway.

import { Host, Self, Optional } from '@angular/core';
  
export class ExampleDirective {  
  constructor(
    @Host() @Self() @Optional() public hostCheckboxComponent : MdlCheckboxComponent,
    @Host() @Self() @Optional() public hostSliderComponent   : MdlSliderComponent
  ) {
    if(this.hostCheckboxComponent) {
      console.log("host is a checkbox");
    } else if(this.hostSliderComponent) {
      console.log("host is a slider");
    }
}

Credit: https://github.com/angular/angular/issues/8277#issuecomment-323678013

junho
  • 3,603
  • 3
  • 18
  • 25
Anthony
  • 7,638
  • 3
  • 38
  • 71
  • When using `@Optional` I get `null` and when I remove `@Optional` I get: > No provider for YouComponent found in NodeInjector – WBuck Aug 15 '23 at 14:56
6

A possible workaround to make the directive generic is to pass the template ref of component as @Input to the directive. This adds a little bit of extra html but it worked better than many other hacks I tried.

@Directive({selector: '[myDirective]'})
export class MyDirective implements OnInit {
  @Input() componentRef: any;
  @Input() propName: string;

  ngOnInit(){
    if (this.componentRef != null) {
      // Access component properties
      this.componentRef[this.propName];
    }
 }
}

Usage in view:

<!-- Pass component ref and the property name from component as inputs -->
<app-component #appComponentRef myDirective [componentRef]="appComponentRef" [propName]="'somePropInComponent'" .... >

Also works with other directives. Use exportAs property of the @Directive decorator to get reference to the directive instance.

<form #myForm="ngForm" myDirective [componentRef]="myForm" [propName]="'ngSubmit'" ....>
AC101
  • 851
  • 8
  • 13
4

You can access the host component using ViewContainerRef.

constructor(private el: ViewContainerRef) {}

ngOnInit() {
    const _component = this.el && this.el.injector && this.el.injector.get(MyComponent);
}

Reference: https://angular.io/api/core/ViewContainerRef

Dharini
  • 41
  • 3
  • If you need to make decisions based on whether the host component is something specific: !!this.el.injector.get(MyComponent, undefined, InjectFlags.Optional) Returns true if MyComponent can be obtained from the injector. Otherwise false. – Joseph Zabinski Jun 22 '22 at 20:36
  • 1
    This is not a good solution, if you know the class in advance (MyComponent), you can inject it directly: `constructor(private component: MyComponent) {` – pmoleri Dec 14 '22 at 18:59
2

I do like this, it works on Angular 9 & 11.

nativeElement is a DOM object, I can dynamicly set current Component's

  1. instance to a custom __component field on nativeElement;

  2. access nativeElement.__component in Directve;

    export class FromItemComponentBase { constructor(private hostElement: ElementRef) { hostElement.nativeElement.__component=this; } }


@Component({
  selector: 'input-error',
  templateUrl: 'component.html'
})
export class FromItemErrorComponent extends FromItemComponentBase {
  constructor(private hostElement: ElementRef) {
    super(hostElement);
  }
}

@Component({
  selector: 'input-password',
  templateUrl: 'component.html'
})
export class FromItemPasswordComponent extends FromItemComponentBase {
  constructor(private hostElement: ElementRef) {
    super(hostElement);
  }
}

@Directive({selector: 'input-error,input-password,input-text'})
export class FormInputDirective {
  component:FromItemComponentBase;

  constructor(private hostElement: ElementRef) {
    this.component=hostElement.nativeElement.__component;
  }
}
shine
  • 610
  • 3
  • 10
2

For Angular 12, this comment pointed me in the right direction for a dirty solution. I know this is not a good way of solving this in principle, but my use case required being able to access the component instance without knowing what it was at write-time, due to separation of concerns across multiple modules.

TL;DR:

class MyDirective {
  constructor(private vcRef: ViewContainerRef) {}

  private getHostComponent(): any {
    return this.vcRef._lContainer[0][8];
  }
}

You can access the ViewContainerRef's _lContainer property, which represents the state associated with the container. This LContainer has an entry at index 0 (internally the HOST constant) which is an LView if the container is on a component node.

The LView, in turn, has an entry at position 8 (internally the CONTEXT constant) which is a reference to the component instance if the component this is attached to is a non-root component element (e.g. <app-*). This means you can access the host context component by accessing lContainer[HOST][CONTEXT].

Long answer to copy-paste with explanations:

class MyDirective {
  constructor(private vcRef: ViewContainerRef) {}

  private getHostElementFromViewContainerRef(): unknown | null {
    // TL;DR of the below method:
    // return this.vcRef._lContainer[0][8];
    // Inspired by https://stackoverflow.com/questions/46014761/how-to-access-host-component-from-directive#comment119646192_48563965

    const vcRef = this.vcRef as any; // We're accessing private properties so we cast to any to avoid awkward TS validation issues

    // We fetch the component associated with the element this directive is attached to by navigating via the ViewContainerRef.
    // The VCRef contains a reference to the LContainer, which represents the state associated with the container:
    // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/container.ts#L65
    const lContainer = vcRef._lContainer;

    if (!lContainer) {
      return null;
    }

    // LView has all its elements defined as array elements, with keys hardcoded to numeric constants:
    // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/view.ts#L26-L57
    // We care about two of them:
    const HOST = 0; // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/view.ts#L29
    const CONTEXT = 8; // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/view.ts#L37

    // LContainer is an array, with the element at the HOST position being an LView if the container is on a Component Node.
    // This means that this may not work if this directive is declared on a native HTML element.
    // Note that LContainer uses the same indexes as LView, so it's the same HOST constant as declared in the LView interfaces file.
    // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/container.ts#L66-L72

    const lView = lContainer[HOST];
    if (!lView) {
      return null;
    }

    // For a non-root component, the context is the component instance.
    // So if this directive is correctly attached to an Angular Component (e.g. `<app-*`),
    // this array entry will contain the instance of that component.
    // https://github.com/angular/angular/blob/12.2.x/packages/core/src/render3/interfaces/view.ts#L173-L180
    const contextElement = lView[CONTEXT];

    return contextElement || null;
  }
}
Pingless
  • 788
  • 1
  • 7
  • 9
1
constructor(private vcRef: ViewContainerRef){
        let parentComponent=(<any>this.vcRef)._view.context;
}
Akshay Bohra
  • 323
  • 3
  • 6
  • 2
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Derek Brown Jun 23 '18 at 02:16
  • `_view.context` implies `_view` should be private and therefore you appear to be doing this in a non-standard way, just as a shout for anyone coming across this later. cite: https://stackoverflow.com/questions/4484424/underscore-prefix-for-property-and-method-names-in-javascript – N.J.Dawson Jul 19 '18 at 15:59
1

Having viewContainerRef: ViewContainerRef in constructor and having following code (this.viewContainerRef as any)._hostLView[8] works perfectly. But it looks hacky, so better to pass the component reference as Input parameter to the directive, as described below.

<my-comp myDirective [hostComponent]="hostComponent"></my-comp>

In myCompComponent.ts,

hostComponent = this;

In myDirective.ts,

@Input() hostComponent: Component;

Jitu
  • 13
  • 6
0

NOTE: this is hacky and will likely not work in future versions of Angular. In Angular 10, I was able to access the host component like this:

Similarly to @Sunil Garg 's solution, inject the ViewContainerRef in the ctor of the directive:

constructor(_viewContainerRef: ViewContainerRef)

Get the host component like this:

let hostComponent = (<any>_viewContainerRef)._lContainer[0][8];

StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
0

I tried two solutions from here:
Michiel Windey's one (using an abstract class as interface for the components where the directive will be used), and Anthony's one (using @Host() @Self() @Optional()).
Both work with Angular 11.
Both are non hacky and are probably future-proof, unlike the hacky solutions using undocumented private fields…

The second one has the advantage to access the existing components without changing them. But you probably need to have lot of checks and special cases to handle, depending on which component is really injected.

The first one has the inconvenience to require the components to be modified, but you can define in the interface (abstract class) all the fields and methods you are going to use in the directive, and thus you can access them with a single parameter, without needing to check what kind of component is injected.

So your choice really depend on your use case.

PhiLho
  • 40,535
  • 6
  • 96
  • 134