在angular2中,如何让子组件彼此通信? [英] In angular2, how to let child components communicate with each other?

查看:78
本文介绍了在angular2中,如何让子组件彼此通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个Parent组件(在其中,有一个Cat和Dog继承自Animal类)和两个子组件(Cat和Dog),cat和dog按钮始终处于相反的状态,请单击cat按钮可以禁用狗"按钮,然后单击狗"按钮可以禁用猫"按钮.我该如何实施?

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 {
}

推荐答案

您可以使用包含类型为EventEmitter的属性的共享服务.这样,您将能够触发事件,并且将通知订阅该事件的所有元素(组件).

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.

  • 共享服务

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');
      }
    }
    

  • 以下是您的用例的示例实现: https://plnkr.co/edit/U7vflPDOUgAG3UCFZG3n?p =预览.

    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:

    这篇关于在angular2中,如何让子组件彼此通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆