Reputation: 1143
Scenario :
I am using angular material tabs, each different tabs have their respective dynamic component.
So when I am switching the tabs, it removes the content from DOM. And when I come back again to that tab, it loads content again.
Problem :
Instead of default behaviour, I just want the content to change to display:none;
instead of removing it from DOM.
Upvotes: 5
Views: 5106
Reputation: 1
Update Aug, 2023: This is now supported by the MatTabGroup component using the preserveContent directive:
Documentation: https://material.angular.io/components/tabs/overview#keeping-the-tab-content-inside-the-dom-while-its-off-screen
Pull Request: https://github.com/angular/components/pull/24299
So to reuse @sshdharmen's example, you can put the content back inside the mat-tab if you add the preserveContent directive to the mat-tab-group:
<mat-tab-group preserveContent>
<mat-tab label="First">
<!-- First tab content -->
</mat-tab>
<mat-tab label="Second">
<!-- Second tab content -->
</mat-tab>
</mat-tab-group>
The tab content is still lazy-loaded, but when you switch tabs it is no longer removed from the DOM.
Upvotes: 0
Reputation: 1463
I don't think that we can change the default behavior of Tabs, as of now.
But, what we can do is, change the structure little bit to achieve expected behavior.
So, we can remove the content from Tabs and handle it separately outside mat-tab-group
. We will check which tab is active and accordingly adjust display
property of respective content.
Overall, the code will look like below:
<mat-tab-group>
<mat-tab label="First" #firstTab>
</mat-tab>
<mat-tab label="Second" #secondTab></mat-tab>
</mat-tab-group>
<div [ngStyle]="{'display':!firstTab.isActive ? 'none' : null}">First</div>
<div [ngStyle]="{'display':!secondTab.isActive ? 'none' : null}">Second</div>
I have also created same example on stackblitz.
Upvotes: 7