Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - how to access directive and call a member function in it

Tags:

angular

ionic2

I have a directive like this -

@Directive({
    selector:   'someDirective'
})
export class  SomeDirective{         
    constructor() {}    
    render = function() {}
}

and then I am importing the directive

import {SomeDirective} from '../../someDirective';
@Page({
    templateUrl: '....tem.html',
    directives: [SomeDirective]
})
export class SomeComponent {
      constructor(){}
      ngAfterViewInit(){//want to call the render function in the directive
}

In ngAfterViewInit, I want to call the render function in the directive. How to do this ?

like image 824
VISHAL DAGA Avatar asked Mar 22 '16 16:03

VISHAL DAGA


1 Answers

This is old way,

@Directive({
    selector:   'someDirective'
})
export class  SomeDirective{         
    constructor() {}    
    render() {
       console.log('hi from directive');
    }
}

import {Component,ViewChild} from 'angular2/core';
import {SomeDirective} from '../../someDirective';
@Component({
    templateUrl: '....tem.html',
    directives: [SomeDirective]
})
export class SomeComponent {
      @ViewChild(SomeDirective) vc:SomeDirective;
      constructor(){}
      ngAfterViewInit(){
          this.vc.render();
      }
}

for newer version of Angular2, follow answer given here

Calling function in directive

like image 82
Nikhil Shah Avatar answered Sep 27 '22 19:09

Nikhil Shah