angular

Calling function in directive


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?


Solution

  • 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();
    }