Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling function in directive

Tags:

angular

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?

like image 924
doorman Avatar asked Nov 05 '16 12:11

doorman


People also ask

Can we call function in Angular?

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.

How do I invoke a directive in AngularJS?

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.

Can we use directive in TS file?

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.


1 Answers

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();
}
like image 56
Nikhil Shah Avatar answered Oct 08 '22 02:10

Nikhil Shah