Child component events broadcast to parent

前端 未结 3 1725
离开以前
离开以前 2020-12-06 07:39

I\'d like to implement the common Angular 1.x pattern of having child directives within a parent directive in Angular 2. Here\'s my desired structure.



        
3条回答
  •  感动是毒
    2020-12-06 08:14

    The other answer does a very poor job of solving the problem. EventEmitters are only meant to be used in conjunction with @Outputs as well as this problem not taking advantage of the dependency injection built into Angular 2 or the features of RxJS.

    Specifically, by not using DI, you're forcing yourself into a scenario where if you reuse the components dependent on the static class they will all receive the same events, which you probably don't want.

    Please take a look at the example below, by taking advantage of DI, it is easy to provide the same class multiple times, enabling more flexible use, as well as avoiding the need for funny naming schemes. If you want multiple events, you could provide multiple versions of this simple class using opaque tokens.

    Working Example: http://plnkr.co/edit/RBfa1GKeUdHtmzjFRBLm?p=preview

    // The service
    import 'rxjs/Rx';
    import {Subject,Subscription} from 'rxjs/Rx';
    
    export class EmitterService {
      private events = new Subject();
      subscribe (next,error,complete): Subscriber {
        return this.events.subscribe(next,error,complete);
      }
      next (event) {
        this.events.next(event);
      }
    }
    
    @Component({
      selector: 'bar',
      template: `
        
      `
    })
    export class Bar {
      constructor(private emitter: EmitterService) {}
      clickity() {
        this.emitter.next('Broadcast this to the parent please!');
      }
    }
    
    @Component({
      selector: 'foo',
      template: `
        
    `, providers: [EmitterService], directives: [Bar] }) export class Foo { styl = {}; private subscription; constructor(private emitter: EmitterService) { this.subscription = this.emitter.subscribe(msg => { this.styl = (this.styl.background == 'green') ? {'background': 'orange'} : {'background': 'green'}; }); } // Makes sure we don't have a memory leak by destroying the // Subscription when our component is destroyed ngOnDestroy() { this.subscription.unsubscribe(); } }

提交回复
热议问题