Angular 2 - 如何访问指令并在其中调用成员函数

时间:2016-03-22 16:37:15

标签: angular ionic2

我有这样的指示 -

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

然后我导入指令

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

在ngAfterViewInit中,我想在指令中调用render函数。 怎么做?

1 个答案:

答案 0 :(得分:13)

这是老路,

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

对于较新版本的Angular2,请按照此处给出的答案

Calling function in directive