Reputation: 2084
I need to get the value of whatever tab the user clicks on. Here's what I have so far:
<mat-tab-group (selectedTabChange)="getLabel($event)" #tabGroup>
<mat-tab label="{{ thing.name }}" *ngFor="let thing of things | async" #tab>
....
</mat-tab>
</mat-tab-group>
TS - Database Fetch:
thingsCollection: AngularFirestoreCollection<Intf>;
things: Observable<Intf[]>;
ngOnInit() {
this.thingsCollection = this.afs.collection(placeToSearch2);
this.things = this.thingsCollection.valueChanges();
}
The issue is that I also need the value of the label
property of the tab that the mat-tab-group
first loads. (selectedTabChange)
only fires when the user manually clicks on a tab. That's good, but doesn't give me the label of the first tab.
There was a similar question here with a good answer, but the commenter seemed to ghost on me when I asked him my particular question more clearly. The answer that he provided was close to what I need:
ngAfterViewInit() {
console.log('afterViewInit => ', this.tabGroup.selectedIndex); // Close, but no cigar
}
The above solution only gives me the index (which is almost always 0), not the label
. How can I get the label? The Angular Tab reference shows there is a textLabel property. I think this might be the answer, but it uses @Input which I'm not familiar with. Can someone please help me use it?
Upvotes: 3
Views: 3424
Reputation: 2880
You should always stick to public apis as much as possible instead of depending on the core implementation because in the future if they change the internals your app will break. You can change your component to look like, add
@ViewChildren(MatTab) tabs: QueryList<MatTab>;
This will query all your tabs and make a query list.
and then in the on init, when your data arrives you should check for the first tab. So in your component you can just do,
ngOnInit() {
this.thingsCollection = this.afs.collection(placeToSearch2);
this.things = this.thingsCollection.valueChanges();
this.things.finally(() => {
setTimeout(() => { this.checkSelection(); });
});
}
checkSelection() {
let tab = this.tabs.first;
console.log('selected tab', tab);
}
This will query the list and will give you the first tab.
Upvotes: 1
Reputation: 34691
You can get it using the following:
this.tabGroup._tabs.first.textLabel
See this StackBlitz demo.
Upvotes: 3