2

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • 1
    `@ViewChild`, as the name implies, will only get template references to things that are children of the component you're defining that. Since there are no instances of `MyDirective` inside of `child-component`, it is undefined. You cannot use `@ViewChild` to reference anything that is not a child of the component you're defining it in. – John Woodruff Apr 14 '23 at 22:57

1 Answers1

1

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.

MikeJ
  • 2,179
  • 13
  • 16