Mayur
Mayur

Reputation: 1143

mat-tab remove the tab-body DOM but not hide it

Scenario :


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

Answers (2)

cparkinson
cparkinson

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

shhdharmen
shhdharmen

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

Related Questions