5

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.

Ismatjon
  • 1,149
  • 1
  • 8
  • 17
Mayur
  • 1,123
  • 3
  • 22
  • 38
  • According to the docs: [By default, the tab contents are eagerly loaded. Eagerly loaded tabs will initalize the child components but not inject them into the DOM until the tab is activated.](https://material.angular.io/components/tabs/overview#lazy-loading) Which sounds very much like what you're asking here. The content of your tab is technically rendered, but it is stored in memory instead of within the DOM. Do you really want to do what you described? – Noah Solomon Jan 22 '19 at 20:41

2 Answers2

7

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.

shhdharmen
  • 1,413
  • 10
  • 20
0

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.