0

Consider these material tabs in my template:

<mat-tab #myFirstTab>Something</mat-tab>
<mat-tab #mySecondTab>Something else</mat-tab>

And the ViewChildren in the .ts file:

  @ViewChildren(MatTab)
  private allTabs: QueryList<MatTab>;

  public ngAfterViewInit() {
    this.allTabs.forEach(tab => console.log('tab: ', tab));
  }

How can I access the actual template references of each tab (#myFirstTab and #mySecondTab) in my .ts code ? Is it possible at all this way around ? I need a way to differentiate my tabs, and the label text is not good because it can vary...

Edit: I specifically asked for @ViewChildren and not @ViewChild. Of course I know the other way around. In this case, I do not want to have to declare each Viewchild in my .ts file.

Tim
  • 3,910
  • 8
  • 45
  • 80
  • Possible duplicate of [How can I select an element in a component template?](https://stackoverflow.com/questions/32693061/how-can-i-select-an-element-in-a-component-template) – Chris Yungmann Oct 30 '19 at 19:48
  • I do not understand what you are trying to accomplish by avoiding the `ViewChild` directive. It seems like you either need something like (imaginary) `const myFirstTab = allTabs.find(tab => tab.templateRefName === 'myFirstTab');` or `@ViewChild('myFirstTab') myFirstTab: MatTab;`. The second approach is both shorter and more idiomatic in Angular (and also exists). – Chris Yungmann Oct 31 '19 at 21:46
  • I am trying to avoid code duplication and boiler plate code. I want to be able to add another Mat Tab without having to add a new explicit ViewChild. – Tim Nov 04 '19 at 11:08

1 Answers1

0

ViewChild directive? e.g.

@ViewChild('myFirstTab') myFirstTab: MatTab;
@ViewChild('mySecondTab') mySecondTab: MatTab;
Chris Yungmann
  • 1,079
  • 6
  • 14
  • I specifically asked for ViewChildren and not ViewChild. Of course I know the other way around. In this case, **I do not want to have to declare each Viewchild in my .ts file – Tim Oct 31 '19 at 20:56