Ng2-Fun
Ng2-Fun

Reputation: 3393

In angular2, how to let child components communicate with each other?

Suppose we have a Parent component(inside it, there is an Animal class that Cat and Dog extends from) with two child components(Cat and Dog), cat and dog button are always in opposite status, click the cat button can make dog button disable, and click the dog button can make the cat button disable. How can I implement it?

@Component
...,
template: `<cat></cat>
           <dog></dog>`
class ParentComponent {
}

export class Animal {
}

@Component
...
class Cat extends Animal {
}

@Component Dog extends Animal {
}

Upvotes: 3

Views: 1587

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202316

You could use a shared service containing a property of type EventEmitter. This way you will be able to trigger an event and all elements (components) that subscribe on this event will be notified.

  • The shared service

    import {EventEmitter} from 'angular2/core';
    
    export class SharedService {
      constructor() {
        this.selected = new EventEmitter();
      }
    
      select(elt) {
        this.selected.emit(elt);
      }
    }
    
  • Sub component implementation (for example the cat one)

    import {Component} from 'angular2/core';
    import {SharedService} from './app.service';
    
    @Component({
        selector: 'cat',
        template: `
          <div (click)="select()">Cat {{disabled}}</div>
        `
    })
    export class CatComponent {
      constructor(private service:SharedService) {
        this.disabled = false;
        service.selected.subscribe((elt) => {
          if (elt==='cat') {
            this.disabled = false;
          } else {
            this.disabled = true;
          }
        });
      }
    
      select() {
        this.service.select('cat');
      }
    }
    

Here is a sample implementation for your use case: https://plnkr.co/edit/U7vflPDOUgAG3UCFZG3n?p=preview.

Don't forget to register the provider corresponding at the bootstrap level to share the same instance.

See this question for more details:

Upvotes: 4

Mark Rajcok
Mark Rajcok

Reputation: 364727

It depends. If the parent component needs to know when the cat button and dog button are clicked, I would specify input and output properties on the child components. emit() an event on the output property when a click event happens that notifies the parent, which can then modify the parent property that is bound to the input property of the other component.

If the parent doesn't need to know what is going on, then you could use a shared service, as @Thierry just mentioned.

Upvotes: 1

Related Questions