4

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?

ktamlyn
  • 4,519
  • 2
  • 30
  • 41
  • Is onMinimized is a custom event emitter? cuz then you can subscribe to it in code. a question though - since tabs is an array, aren't you looping through that array to create the TabComponents? or are you creating the tabs a different way? – snorkpete Apr 24 '17 at 19:32
  • Each tab is defined in the template (though they could be in an array I suppose). How do I create an event listener to an angular "output" of a ContentChild via a ContentChild reference? – ktamlyn Apr 24 '17 at 20:32
  • Found this, but its not exactly what I'm looking for. http://stackoverflow.com/questions/37746058/what-is-the-best-way-to-detect-focus-event-in-contentchild-in-angular2 – ktamlyn Apr 24 '17 at 20:43
  • can you post the component code for one of your tabs? – snorkpete Apr 24 '17 at 21:53

1 Answers1

11

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.

ktamlyn
  • 4,519
  • 2
  • 30
  • 41