问题
I have a requirement for adding dynamic tabs to some User Preferences
screen.
The main preference tab can be a static tab with static content, but the second tab should have nested mat-tab
elements.
These additional dynamic preferences come from the backend, which then allows me to use an *ngFor
to render the extra tabs.
Problem I'm seeing now is with the tab labels
. The label text is taking its value from the first nested tab, and NOT from the label
property I'm setting.
Please see my example here on stackblitz - https://stackblitz.com/edit/mat-tabs-nested?embed=1&file=app/tab-group-async-example.html
A code snippet from the online project is:
<mat-tab-group>
...
<mat-tab label="More Dynamic Preferences">
<!-- NESTED HERE -->
<mat-tab-group>
<mat-tab *ngFor="let tab of asyncTabs | async">
<ng-template mat-tab-label>{{tab.label}}</ng-template>
{{tab.content}}
</mat-tab>
</mat-tab-group>
</mat-tab>
</mat-tab-group>
If you click on "More Dynamic Preferences" tab, then the tab header text becomes "First". Same happens on the second tab, whose tab content I'm loading synchronous, as opposed to the async example.
回答1:
This issue is being caused by the way label is being set for tab.
You are setting label of parent with attribute label however for child tab you had used the template way to define it.
<ng-template mat-tab-label>{{tab.label}}</ng-template>
So what you can do is either you define the label of parent tab same or just add label attribute for the child tabs too.
Here is working copy - https://stackblitz.com/edit/mat-tabs-nested-n77qed
回答2:
I'm not sure what the purpose of the <ng-template>
s are in the <mat-tabs>
elements, but after removing those, add some bindings to the label
input of the tab components, and refactoring the async call to not use setTimeout()
and use native rxjs operations, I have a working demo of using nested tabs with dynamic tab creation:
<mat-tab label="Customer Preferences">
<h2>HERE ARE YOUR PREFERENCES</h2>
</mat-tab>
<mat-tab label="Dynamic Preferences">
<mat-tab-group>
<mat-tab *ngFor="let tab of prefTabs" [label]="tab.label">
{{tab.content}}
</mat-tab>
</mat-tab-group>
</mat-tab>
<mat-tab label="More Dynamic Preferences">
<mat-tab-group>
<mat-tab *ngFor="let tab of asyncTabs | async" [label]="tab.label">
{{tab.content}}
</mat-tab>
</mat-tab-group>
</mat-tab>
Updated stackblitz
来源:https://stackoverflow.com/questions/53194896/nested-angular-material-tabs