在 Angular2 中使用路由器(路由器插座)实现 'Master - detail'

Implementing 'Master - detail' with router (router outlet) in Angular2

我正在使用 Angular2 路由器实现主从屏幕。 我有一个组件,它在其模板中定义了一个资源列表(ul/li 格式):主要部分。列表中的每个资源都可以通过 "routerLink" 绑定点击。

在同一个模板中,我定义了一个路由器插座。这个想法是:当我单击列表中的一个资源时 (ul/li),Angular2 应该 display/render 在路由器出口点的可编辑表单。我可以更改数据并按保存按钮。 (细节部分)

当这个资源被更新(保存)时,我希望资源列表(ul/li)也被更新,因为可能一些数据已经改变,它也显示在资源列表中(例如资源显示名称)。

由于 Angular2 正在管理细节组件,因此我没有在我的 html 模板中声明该组件。但是,因为我没有声明细节组件,所以我没有钩子来对事件(如更改事件)做出反应。也就是说,当我的表格被成功更改时,我会发出一个 "change event"。基于这样的事件,我可以在 'Master part' 处实现一个处理程序,以便主控可以通过刷新资源列表 (ul/li) 来更新自身。

关键是:由于在我的应用程序中引入了 Angular2 路由器功能,我失去了主组件和从组件之间的关系。

问题:有没有办法解决这个问题?

理想的方式是使用,Component communication via a service

你也可以在下面试试,

import { Component , Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'my-app',
  template: `Angular Route
   <hr />
    <a routerLink="/child1" >Child 1</a>
    <a routerLink="/child2" >Child 2</a>
  <hr />
     Inside Parent component
     <br />
     <br />
     Subscription from child : {{result | json}}
  <hr />
  <div> Child Component</div>
  <br />
  <router-outlet
  (activate)='onActivate($event)'
  (deactivate)='onDeactivate($event)'></router-outlet>
  `
})
export class AppComponent {
  result: any = {};

  constructor(){
  }

  childSubscription: any;

  onActivate($event){
     if(!!$event['parentNotifier']){
       this.childSubscription = $event['parentNotifier'].subscribe(res => {
          this.result = res;
       });
     }
  }

  onDeactivate($event){
    if(!!this.childSubscription){
      this.childSubscription.unsubscribe();
    }
  }
}

@Component({
  selector: 'my-app',
  template: `I am a child
  <button (click)='clickMe()' >Click me to notify parent</button>
  `
})
export class ChildComponent1 {
   @Output() parentNotifier:EventEmitter<any> = new EventEmitter<any>();

   clickMe(){
     this.parentNotifier.next('I am coming from child 1!!');
   }
}

@Component({
  selector: 'my-app',
  template: `I am a child
  <button (click)='clickMe()' >Click me to notify parent</button>
  `
})
export class ChildComponent2 {
   @Output() parentNotifier:EventEmitter<any> = new EventEmitter<any>();

   clickMe(){
     this.parentNotifier.next('I am coming from child 2!!');
   }
}

但是请注意,事件的名称需要以某种方式被父级知道,就像在上面的示例中一样,我直接使用了它parentNotifier

这里是 Plunker!!

希望对您有所帮助!!