19

I am trying to call a public function which is inside my directive from component by getting hold of the directive via viewchild like this

 @ViewChild('myDirective') myDirective;
 ....
 myDirective.nativeElement.myFunction();

But I get error that the myFunction does not exist. Is there a way to call a function which is iniside a directive?

doorman
  • 15,707
  • 22
  • 80
  • 145
  • checkout this as well https://netbasal.com/angular-2-take-advantage-of-the-exportas-property-81374ce24d26#.fxcc4c7vf – Ayyash Mar 11 '17 at 10:31
  • This shows how you can do it using a template variable: https://stackoverflow.com/a/36345948/222748 – Michael May 25 '17 at 06:57

2 Answers2

27

DEMO - How to call Directive's function from Component - check browser's console


1) I hope you are importing myDirective directive.
import {myDirective} from './Directive';

2)

@ViewChild(myDirective) vc:myDirective;   ///<<<@@@removed '' from ('myDirective')

3)

ngAfterViewInit(){   
    this.vc.myFunction();                 ///<<@@@ no need to use nativeElement
}

4) Or some button's click event

click(){
   this.vc.myFunction();
}
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • Thanks, this worked with ViewChild and by setting the directive instead of the #myDirective I was using with the ''. But it makes wonder how to accomplish this when using multiple directives. In this case I am only using one directive. – doorman Nov 05 '16 at 13:47
  • With multiple directives mean how and what???. Ask question and get answer. tell us your scenario and we'll try to resolve it. – micronyks Nov 05 '16 at 13:49
  • Thanks, what I mean is if you have e.g. from your plunkr

    Angular2

    Test 3

    How would you reference the h3 directive
    – doorman Nov 05 '16 at 13:52
  • Could you please ask it as a separate question? – micronyks Nov 05 '16 at 14:13
  • 1
    just what i was looking for, awesome find! – TrieuNomad Dec 06 '16 at 00:15
  • @doorman You could try `@ViewChildren(Type)` instead then call ToArray and access by index. – Michael May 25 '17 at 06:51
  • 1
    This seems deprecated. Cannot read property 'callme' of undefined. please see https://stackblitz.com/edit/angular-playground-1di2vk?file=app/app.component.ts – Vincent Aug 16 '18 at 11:51
9

Use @ContentChild(). A directive doesn't have a view.

Call this.myDirective.nativeElement.myFunction() in ngAfterContentChecked() to ensure that this.myDirective... is already initialized.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567