Search code examples
angulartypescriptangular6angular-services

Communication between re usable components using services


I have created two generic components called 1)list and 2)details so that i can re use them:

The components looks like this:

enter image description here

Now i am re using the these component in another components called SCHOOL and COLLEGE which will displayed like this:

enter image description here

Now

  • If i click on the list-item(for ex school 1) from the list component present in SCHOOL component. I want to display that particular clicked item details(Ex: Name,email) on right side (i,e on details page/component).

  • If i click on the list-item(for ex college 1) from the list component present in COLLEGE component. I want to display that particular clicked item details(Ex: Name,email) on right side (i,e on details page/component).

I got solution by this question . In this example communication is happening between the components using services. But in my condition i am re using the component. How can i use the services when i am re using the component.

Stackblitz DEMO


Solution

  • In your current scenario, the best would be to leverage @Input and @Output decorators.

    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>
    

    Here is the working copy - https://stackblitz.com/edit/list-examples-mine-ilxisk