title: Communication between sibling components in angular
body: <p>I have two sibling components and one needs to send data to the other one. The communication should happen between the heroes component and encounters component:</p>
  
  <pre><code>&lt;section id="Dashboard" &gt;
   &lt;app-heroes&gt;&lt;/app-heroes&gt;
  
   &lt;app-monsters&gt;&lt;/app-monsters&gt;
  
   &lt;app-encounters&gt;&lt;/app-encounters&gt;
  &lt;/section&gt;
  </code></pre>
  
  <p>I have <a href="https://imgur.com/a/opIAWiJ" rel="nofollow noreferrer">uploaded the UI to imgur</a> to clarify the issue. When someone clicks on one of the heroes, the hero that has been clicked should be added to "Heroes" in the encounter component.</p>
  
  <p>I created a shareservice:</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import {Subject} from 'rxjs';
  import {Hero} from '../model/hero';
  
  @Injectable({
  providedIn: 'root'
  })
  export class SharedHeroService {
   private hero = new Subject&lt;Hero&gt;();
   public  hero$ = this.hero.asObservable();
  
   publishHero(heroToPublish: Hero){
    this.hero.next((heroToPublish));
   }  
  }
  </code></pre>
  
  <p>for which I created the following method in my heroes component:</p>
  
  <pre><code>addToEncounter(hero){
  this.sharedService.publishHero(hero);
  }
  </code></pre>
  
  <p>and added the following in my Encounters component:</p>
  
  <pre><code>@Input() public heroesAdded = [];
  @Input() hero: Hero;
  private subscriber: Subscription;
  
  constructor(private sharedHeroService: SharedHeroService) {}
  
  ngOnInit() {
  this.subscriber = this.sharedHeroService.hero$.subscribe(hero =&gt;{this.hero = 
  hero; this.monstersAdded.push(hero)});
  }
  </code></pre>
  
  <p>The html for the Heroes component is:</p>
  
  <pre><code>&lt;ul class="heroes"&gt;
  &lt;li *ngFor="let hero of heroes"&gt;
    &lt;span class="badge" onclick="addToEncounter(hero)"&gt;{{hero.name}}&lt;/span&gt; 
  Hitpoints: {{hero.hitPoints}} Armor: {{hero.armor}}
  &lt;/li&gt;
  </code></pre>
  
  <p></p>
  
  <p>But when I click on the badge, I get the following error:</p>
  
  <p>Uncaught ReferenceError: addToEncounter is not defined
      at HTMLSpanElement.onclick</p>
  
  <p>I googled this and people are saying the onclick() should never be used, but I don't really get the alternatives?</p>