Angular 2子组件事件广播到父级

时间:2016-01-15 00:13:35

标签: typescript angular angular2-directives

我想在Angular 2中的父指令中实现具有子指令的常见Angular 1.x模式。这是我想要的结构。

<foo>
  <bar>A</bar>
  <bar>B</bar>
  <bar>C</bar>
</foo>

我希望这些Bar组件能够将点击事件发送到Foo组件。

到目前为止,这是我的Foo

@Component({
  selector: 'foo',
  template: `
    <div>
      <ng-content></ng-content>
    </div>
  `
})
export class Foo {
   @ContentChildren(Bar) items: QueryList<Bar>;
}

这是我的Bar

@Component({
  selector: 'Bar',
  template: `
    <div (click)="clickity()">
      <ng-content></ng-content>
    </div>
  `
})
export class Bar {
  clickity() {
    console.log('Broadcast this to the parent please!');
  }
}

如果点击其中一个Foo,如何通知Bars

3 个答案:

答案 0 :(得分:14)

如果您无法使用@Output()装饰器执行此操作,则可以使用服务在组件之间发送数据。这是一个例子:

import {EventEmitter} from 'angular2/core';

export class EmitterService {
  private static _emitters: { [channel: string]: EventEmitter<any> } = {};
  static get(channel: string): EventEmitter<any> {
    if (!this._emitters[channel]) 
      this._emitters[channel] = new EventEmitter();
    return this._emitters[channel];
  }
}

您可以在需要发出或订阅活动的任何地方导入它:

// foo.component.ts
import {EmitterService} from '../path/to/emitter.service'

class Foo {
  EmitterService.get("some_id").subscribe(data => console.log("some_id channel: ", data));
  EmitterService.get("other_id").subscribe(data => console.log("other_id channel: ", data));
}

// bar.component.ts
import {EmitterService} from '../path/to/emitter.service'

class Bar {

  onClick() {
    EmitterService.get("some_id").emit('you clicked!');
  }
  onScroll() {
    EmitterService.get("other_id").emit('you scrolled!');
  }
}

另一个例子:plunker

答案 1 :(得分:5)

另一个答案在解决问题方面做得很差。 EventEmitters仅用于与@Outputs一起使用以及此问题,而不利用Angular 2中内置的依赖注入或RxJS的功能。

具体来说,如果不使用DI,你就会强迫自己进入一个场景,如果你重复使用依赖于静态类的组件,他们都会收到你可能不想要的相同事件。 / p>

请看下面的例子,利用DI,很容易多次提供同一个类,使用更灵活,同时避免使用有趣的命名方案。如果您想要多个事件,可以使用opaque标记提供此简单类的多个版本。

工作示例: 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: `
    <button (click)="clickity()">click me</button>
  `
})
export class Bar {
  constructor(private emitter: EmitterService) {}
  clickity() {
    this.emitter.next('Broadcast this to the parent please!');
  }
}

@Component({
  selector: 'foo',
  template: `
    <div [ngStyle]="styl">
      <ng-content></ng-content>
    </div>
  `,
  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();
  }
}

答案 2 :(得分:3)

为什么不使用@ContentChildern?

在bar.component.ts中的

,我们公开了点击的事件

@Output() clicked = new EventEmitter<BarComponent>();
onClick(){
    this.clicked.emit(this);
}

在foo.component.ts中,我们订阅了每个

的点击事件
 @ContentChildren(BarComponent) accordionComponents: QueryList<BarComponent>;

 ngAfterViewInit() {
 this.accordionComponents.forEach((barComponent: BarComponent) => {
        barComponent.clicked.subscribe((bar: BarComponent) => doActionsOnBar(bar));           
    });
}
相关问题