10

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 ?

VISHAL DAGA
  • 4,132
  • 10
  • 47
  • 53

1 Answers1

13

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

Community
  • 1
  • 1
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • Thanks for the answer, I have tried this as you told, but I am getting error - syntax error - @ViewChild(SomeDirective) vc:SomeDirective; at the colon ':' of the line. I am using Ionic 2. I tried importing both ways --->import {ViewChild} from 'angular2/core'; and import {ViewChild} from 'ionic-angular'; – VISHAL DAGA Mar 22 '16 at 18:09
  • Oops! I don't Ionic framwork. so can't help you in that case. But I'm sure this is how ViewChild is used. – micronyks Mar 22 '16 at 18:15
  • hey you are absolutely correct, except that I am writing code in ES6. So, wrote the code in TS and transpiled it and things worked. It would be great if you can tell me how to write the same in ES6/ES5. Thanks. – VISHAL DAGA Mar 22 '16 at 18:26
  • Its hard to tell you from my end as I'm also writing my stuffs in TS only. But I'm sure it won't be tough to figure out if you want to write it in ES6. – micronyks Mar 22 '16 at 18:29