angularangular-directiveviewchild

how to access a directive from another peer component


I have a component and a directive inside a parent component. The parent component template looks like this:

<div>
     <child-component></child-component>
     <dx-data-grid
          my-directive></dx-data-grid>
</div>

Is there a way to get a reference to 'my-directive' from within the 'child-component'?

I tried to use @ViewChild from within the 'child-component' class like:

@ViewChild(MyDirective) directiveReference: MyDirective;

This comes up as undefined.


Solution

  • To get a reference to the directive on the sibling component, you can use a template variable along with the Directive exportAs option, which (from the docs) "defines the name that can be used in the template to assign this directive to a variable."

    First, in the MyDirective class, add an exportAs option (if it's not already defined):

    @Directive({
      selector: '[my-directive]',
      exportAs: 'myDirective', // <--- add this (use whatever name you want)
    })
    export class MyDirective {
    }
    
    

    Then, in the child-component class, define an Input that will accept the directive reference:

    @Component({
      selector: 'child-component',
    })
    export class ChildComponent {
      @Input() directiveOnSibling: MyDirective; // <--- add this
    }
    
    

    Finally, in the template, wire it all up by assigning the directive to a template variable (targetDirective, in my example), and passing that variable into child-component using the Input you defined:

    <div>
      <child-component
        [directiveOnSibling]="targetDirective" <-- pass template var to component Input
      ></child-component>
      <dx-data-grid
        my-directive
        #targetDirective="myDirective" <-- assign directive to template var using its exportAs name
      ></dx-data-grid>
    </div>
    

    Here's a StackBlitz showing this approach.