Angular2儿童 - 儿童交流

时间:2017-02-28 19:23:57

标签: angular angular2-template

如何在Angular2中执行儿童 - 通信? Angular2 Documentation描述了执行父子通信的多种方式。但是,父母如何将包含的相互交互?一个孩子可以捕获另一个孩子发出的偶数吗?到目前为止,我的尝试都失败了,我想知道是否有人有一个良好的儿童 - 儿童沟通模式。

例如,如何连接这两个子组件以听取彼此发出的事件?这是我到目前为止的尝试:

@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;
...
}

2 个答案:

答案 0 :(得分:1)

您可以使用

等模板变量
  <app-countdown-timer #countdown 
    (onResetTimer)="buildplan.resetCountDownTimer()"></app-countown-timer>        
  <app-buildplan #buildplan 
    (onTimedOut)="countdown.perfomTimeOutAction()"></app-buildplan>

此示例从兄弟中调用事件处理程序。不确定这是否与您尝试的完全相同。

答案 1 :(得分:0)

我想到了这一点,至少对于通过事件进行的儿童 - 儿童交流。事实证明,onTimedOut发出的app-countdown-timer事件需要在其自己的选择器中监听,即<app-countdown-timer (onTimedOut)="..">。其他组件也是如此。 类中的@ViewChild(BuildPlanComponent) private buildPlan: BuildPlanComponent;允许访问&#34; builplan&#34;父模板中的组件(即(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;
...
}