Arun Kumar Subburaj
Arun Kumar Subburaj

Reputation: 47

@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

Upvotes: 2

Views: 2666

Answers (1)

yurzui
yurzui

Reputation: 214007

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:

Upvotes: 5

Related Questions