2016-04-03 7 views
0

私はディレクティブとページ(実際のコードの簡略化バージョン)を持っています。 myMethodがイベントを介して呼び出されると、myPages isTrueメソッドがtrueになる必要がありますが、ディレクティブからそのページの変数にアクセスする方法がわかりません。これどうやってするの? PS。私はAngular2に基づいてIonic2と呼ばれるフレームワークを使用しています。あなたが@Outputデコレータを使用してディレクティブの中にカスタムイベントを使用することができカスタムディレクティブからページの変数にアクセスする

@Directive({ 
    selector: '[mySelector]' 
}) 

export class myDirective { 

    constructor() { 
    } 

    myMethod() { 
     //Make myPage's isTrue equal to true; 

    } 

} 


@Page({ 
    templateUrl: 'build/pages/myPage/myPage.html', 
    directives: [myDirective] 
}) 
export class myPage{ 

    isTrue= false; 

    constructor() {} 
} 
+1

私が言うことができ、表示することができれば、より良いでしょう。1.どのように私はmyPageで指示を使用しましたか? 2.あなたの.htmlはどのように見えますか? – micronyks

+1

[チュートリアル](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent) –

答えて

0

:コンポーネントで

@Directive({ 
    selector: '[mySelector]' 
}) 
export class myDirective { 
    @Output() 
    customEvent:EventEmitter<boolean> = new EventEmitter(); 

    myMethod() { 
    this.customEvent.emit(true); 
    } 

    // Just a way to call the myMethod method 
    ngAfterViewInit() { 
    setTimeout(() => { 
     this.myMethod(); 
    }, 1000); 
    } 
} 

、イベントがisTrueプロパティを更新するには、この方法をキャッチすることができます

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div mySelector (customEvent)="updateIsTrue($event)"></div> 
    <div>isTrue = {{isTrue}}</div> 
    `, 
    directives: [ myDirective ] 
}) 
export class AppComponent { 
    isTrue= false; 

    updateIsTrue() { 
    this.isTrue = true; 
    } 
} 

このplunkrをサンプルとして参照してください:https://plnkr.co/edit/yuFTwMqYVNJ2awcK02gf?p=preview

別のオプションは、コンポーネントを指令に注入することです。このためには、クラスの巻き上げがサポートされていないため、forwardRef機能を活用する必要があります:https://plnkr.co/edit/jOlEWZzilTId3gruhu9B?p=preview

@Directive({ 
    selector: '[mySelector]' 
}) 
export class myDirective { 
    constructor(@Inject(forwardRef(() => AppComponent)) private host: AppComponent) { 

    } 

    myMethod() { 
    this.host.isTrue = true; 
    } 

    ngAfterViewInit() { 
    setTimeout(() => { 
     this.myMethod(); 
    }, 1000); 
    } 
} 

このplunkrを参照してください。

関連する問題