2017-02-28 6 views
1

どのように実行しますか子供 - 子供はAngular2で通信しますか? Angular2 Documentationは、多くの実行方法を説明しています親子の通信。しかし、子どもがに含まれている場合、親はどのように相互作用するのでしょうか? 1人の子供が別の子供によって放出されたものを捕まえることこれまでの私の試みは失敗しました。誰かがチャイルド・チャイルド・コミュニケーションの良いパターンを持っているかどうかを知りたいと思います。角2子どものコミュニケーション

たとえば、これら2つの子コンポーネントを結び付けて、互いに放出されたイベントを聞くにはどうすればよいですか?

@Component({ 
    template: ` 
    <section>   
     <app-countdown-timer (onResetTimer)="countdownTimerComponent.resetCountDownTimer()"></app-countown-timer>   
     <app-buildplan (onTimedOut)="buildPlan.perfomTimeOutAction()"></app-buildplan> 
    </section> 
`, 
... 
}) 
export class CreateBuildplanComponent implements OnInit { 
    @ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent; 
    @ViewChild(CountdownTimerComponent) private countdownTimerComponent:CountdownTimerComponent; 
... 
} 
+0

へのアクセスを可能にする私は、これは明示的にどこにでも呼ん見ていないが、私はあなたが使用することができることを期待したいですスコープ全体でイベントバスとしてアクセス可能なObservableを作成するために、親コンポーネントレベルのインジェクタを使用します。 –

+0

@Amyそれはいい考えです。もっと複雑なユースケースでは、それがどのように役立つのか分かります。あなたは例を投稿できますか? – JohnV

+0

申し訳ありませんが、「Angular 2 Component Event Bus」で検索し、ポップアップが表示される場合があります。 –

答えて

1

あなたは

<app-countdown-timer #countdown 
    (onResetTimer)="buildplan.resetCountDownTimer()"></app-countown-timer>   
    <app-buildplan #buildplan 
    (onTimedOut)="countdown.perfomTimeOutAction()"></app-buildplan> 

この例では、兄弟からイベントハンドラを呼び出すようにテンプレート変数を使用することができます。これは、これまでの私の試みです。これがまさにあなたがやろうとしたことなのかどうかは分かりません。

+0

これはまさに私が探していたものです。ありがとうございました。 – JohnV

0

私は、少なくともイベントてお子様子供のコミュニケーションのために、これを考え出しました。それは、app-countdown-timerニーズによって放出されるonTimedOutイベントは、それ自身のセレクタ、すなわち<app-countdown-timer (onTimedOut)="..">ににlistendされることが判明しました。他のコンポーネントについても同様です。 クラスの@ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent;は、親テンプレートで「builplan」コンポーネント(すなわち(onTimedOut)="buildPlan.perfomTimeOutAction()"

@Component({ 
    template: ` 
    <section>   
     <app-countdown-timer (onTimedOut)="buildPlan.perfomTimeOutAction()"></app-countown-timer>   
     <app-buildplan (onResetTimer)="countdownTimerComponent.resetCountDownTimer()"></app-buildplan> 
    </section> 
`, 
... 
}) 
export class CreateBuildplanComponent implements OnInit { 
    @ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent; 
    @ViewChild(CountdownTimerComponent) private countdownTimerComponent:CountdownTimerComponent; 
... 
} 
関連する問題