ktamlyn
ktamlyn

Reputation: 4719

How do I listen to a ContentChild event without hooking up via template?

I need to listen for an event from an array of tab components. These tabs emit "onMinimized" however I would rather hook up to these events in one line of code than entering (onMinimized)="hide" for each tab component entry in the template. There is an array of ContentChildren that I have which I can loop through.

I want to do something similar to has follows in the parent:

@ContentChildren(TabComponent) tabs: QueryList<TabComponent>;

...

ngAfterContentInit() {
  this.tabs.map((t: TabComponent) => {
    t.addEventListener("onMinimized", this.hide);
  });
}

hide() {
  // hide tabs
}

Thoughts?

Upvotes: 5

Views: 3451

Answers (1)

ktamlyn
ktamlyn

Reputation: 4719

Figured it out after some trial and error.

  ngAfterContentInit() {
    this.tabs.map((t: TabComponent) => {
      t.minimizeTab.subscribe(() => { this.hide(); })
    });
  }

The way to approach the problem was to consider that the component had a property which was an EventEmitter (just like all angular Outputs). EventEmitters are observables, so you can simply subscribe to the stream of events.

Upvotes: 14

Related Questions