2016-03-22 2 views
8

私はこのようなディレクティブがある -角度2 - どのようにディレクティブをアクセスし、メンバ関数を呼び出すために

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

、その後、私はディレクティブngAfterViewInitで

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

をインポートしていますが、私が欲しいですディレクティブのrender関数を呼び出す。 これを行う方法は?

答えて

12

これは古い方法で、

@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

+0

答えてくれてありがとうを与え従わエラーが発生しています - 構文エラー - @ViewChild(SomeDirective)vc:SomeDirective;行のコロン ':'で始まります。私はイオン2を使用しています。両方の方法をインポートしようとしました.-> import {ViewChild} from 'angular2/core'; {ViewChild}を 'ionic-angular'からインポートします。 –

+0

おっと!私はイオンフレームワークではない。その場合、あなたを助けることはできません。しかし、私はこれがViewChildの使用方法であると確信しています。 – micronyks

+0

あなたは絶対に正しいですが、私はES6でコードを書いています。だから、TSにコードを書いて、それを蒸散して、物事が働いた。 ES6/ES5で同じように書く方法を教えてもらえれば幸いです。ありがとう。 –

関連する問題