Search code examples
angularangular5angular-directive

@viewchild for directive always return element ref instead of directive reference- angular5


I am currently working on a project where I need to pass some @input values based on component. So, that the directive will work accordingly. But the problem is I couldn't get reference of that directive. Instead I only got the elementRef in return. Please refer the below stackblitz sample for more reference.

https://stackblitz.com/edit/angular-feptw3


Solution

  • There are to ways to fix it:

    1) Using read option:

    @ViewChild("myCustomDir", { read: MyCustomDirective}) myCustomDir: MyCustomDirective;
    

    Example

    See also:

    2) Using exportAs

    directive.ts

    @Directive({
      selector: "[myCustom]",
      exportAs: 'myCustom'
      ^^^^^^^^^^^^^^^^^^^^
    })
    export class MyCustomDirective {
      ...
    }
    

    html

    <h1 myCustom #myCustomDir="myCustom">
                               ^^^^^^^^
    

    Example

    See also: