使用服务的可重用组件之间的通信

Communication between re usable components using services

我创建了两个 generic components,名为 1)list2)details,以便我可以重新使用它们:

组件如下所示:

现在我在另一个名为 SCHOOLCOLLEGE 的组件中重新使用这些组件,它们将显示如下:

现在

我通过这个 得到了解决方案。在此示例中,组件之间使用 services 进行通信。 但在我的情况下,我正在重新使用组件。我如何在重新使用组件时使用 services

Stackblitz DEMO

在您当前的情况下,最好的办法是利用 @Input@Output 装饰器。

You need to have @Input for details component which can get the contact details from its component

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent {

  @Input()
  public contact;

}

List component will emit the value on selection of any items from the list.

export class ListComponent {

  @Output()
  public select;

  public onSelect(contact){
     this.select.emit(contact);
  }

}

School and College component can get the the emitted value from the List Component and pass it to details component .

<div class="header">
   <h3>SCHOOL</h3>
  <div  class="left">
      <app-list  [contacts]="contacts" ></app-list>
  </div>
    <div  class="right">
      <app-details></app-details>  
    </div>
</div>

这是工作副本 - https://stackblitz.com/edit/list-examples-mine-ilxisk