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?
Calling a function or initializing a single value on page load in AngularJS is quite easy. AngularJS provides us with a dedicated directive for this specific task. It's the ng-init directive. Example 1: In this example, we will call a function to initialize a variable on page load.
In addition to all the built-in AngularJS directives, you can create your own directives. New directives are created by using the . directive function. To invoke the new directive, make an HTML element with the same tag name as the new directive.
directive. ts file in src/app folder and add the code snippet below. Here, we are importing Directive and ElementRef from Angular core. The Directive provides the functionality of @Directive decorator in which we provide its property selector to appHighLight so that we can use this selector anywhere in the application.
DEMO - How to call Directive's function from Component - check browser's console
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With