Skip to content

Commit 53b4cb2

Browse files
committed
feat(material/tabs): add the ability to keep content inside the DOM while off-screen
Adds the `preserveContent` input which allows consumers to opt into keeping the content of off-screen tabs inside the DOM. This is useful primarily for edge cases like iframes and videos where removing the element from the DOM will cause it to reload. One gotcha here is that we have to set `visibility: hidden` on the off-screen content so that users can't tab into it. Fixes #19480.
1 parent b25283c commit 53b4cb2

File tree

13 files changed

+168
-11
lines changed

13 files changed

+168
-11
lines changed

src/components-examples/material/tabs/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ import {TabGroupHarnessExample} from './tab-group-harness/tab-group-harness-exam
1919
import {TabGroupDynamicExample} from './tab-group-dynamic/tab-group-dynamic-example';
2020
import {TabGroupHeaderBelowExample} from './tab-group-header-below/tab-group-header-below-example';
2121
import {TabGroupLazyLoadedExample} from './tab-group-lazy-loaded/tab-group-lazy-loaded-example';
22+
import {
23+
TabGroupPreserveContentExample
24+
} from './tab-group-preserve-content/tab-group-preserve-content-example';
2225
import {TabGroupStretchedExample} from './tab-group-stretched/tab-group-stretched-example';
2326
import {TabGroupThemeExample} from './tab-group-theme/tab-group-theme-example';
2427
import {TabNavBarBasicExample} from './tab-nav-bar-basic/tab-nav-bar-basic-example';
@@ -37,6 +40,7 @@ export {
3740
TabGroupStretchedExample,
3841
TabGroupThemeExample,
3942
TabNavBarBasicExample,
43+
TabGroupPreserveContentExample,
4044
};
4145

4246
const EXAMPLES = [
@@ -53,6 +57,7 @@ const EXAMPLES = [
5357
TabGroupStretchedExample,
5458
TabGroupThemeExample,
5559
TabNavBarBasicExample,
60+
TabGroupPreserveContentExample,
5661
];
5762

5863
@NgModule({
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<p>Start the video in the first tab and navigate to the second one to see how it keeps playing.</p>
2+
3+
<mat-tab-group [preserveContent]="true">
4+
<mat-tab label="First">
5+
<iframe
6+
width="560"
7+
height="315"
8+
src="https://www.youtube.com/embed/B-lipaiZII8"
9+
frameborder="0"
10+
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
11+
allowfullscreen></iframe>
12+
</mat-tab>
13+
<mat-tab label="Second">Note how the video from the previous tab is still playing.</mat-tab>
14+
</mat-tab-group>
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import {Component} from '@angular/core';
2+
3+
/**
4+
* @title Tab group that keeps its content inside the DOM when it's off-screen.
5+
*/
6+
@Component({
7+
selector: 'tab-group-preserve-content-example',
8+
templateUrl: 'tab-group-preserve-content-example.html',
9+
})
10+
export class TabGroupPreserveContentExample {}

src/material-experimental/mdc-tabs/tab-group.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
[position]="tab.position!"
6262
[origin]="tab.origin"
6363
[animationDuration]="animationDuration"
64+
[preserveContent]="preserveContent"
6465
(_onCentered)="_removeTabBodyWrapperHeight()"
6566
(_onCentering)="_setTabBodyWrapperHeight($event)">
6667
</mat-tab-body>

src/material-experimental/mdc-tabs/tab-group.spec.ts

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,44 @@ describe('MDC-based MatTabGroup', () => {
642642

643643
expect(tabGroupNode.classList).toContain('mat-mdc-tab-group-inverted-header');
644644
});
645+
646+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
647+
fixture.componentInstance.preserveContent = true;
648+
fixture.detectChanges();
649+
650+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
651+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
652+
653+
tabGroup.selectedIndex = 3;
654+
fixture.detectChanges();
655+
tick();
656+
657+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
658+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
659+
}));
660+
661+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
662+
const contentElements: HTMLElement[] =
663+
Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab-body-content'));
664+
665+
expect(contentElements.map(element => element.style.visibility))
666+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
667+
668+
tabGroup.selectedIndex = 2;
669+
fixture.detectChanges();
670+
tick();
671+
672+
expect(contentElements.map(element => element.style.visibility))
673+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
674+
675+
tabGroup.selectedIndex = 1;
676+
fixture.detectChanges();
677+
tick();
678+
679+
expect(contentElements.map(element => element.style.visibility))
680+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
681+
}));
682+
645683
});
646684

647685
describe('lazy loaded tabs', () => {
@@ -1029,7 +1067,7 @@ class AsyncTabsTestApp implements OnInit {
10291067

10301068
@Component({
10311069
template: `
1032-
<mat-tab-group>
1070+
<mat-tab-group [preserveContent]="preserveContent">
10331071
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
10341072
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
10351073
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -1038,6 +1076,7 @@ class AsyncTabsTestApp implements OnInit {
10381076
`
10391077
})
10401078
class TabGroupWithSimpleApi {
1079+
preserveContent = false;
10411080
otherLabel = 'Fruit';
10421081
otherContent = 'Apples, grapes';
10431082
@ViewChild('legumes') legumes: any;

src/material/tabs/tab-body.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,9 @@ export class MatTabBodyPortal extends CdkPortalOutlet implements OnInit, OnDestr
8888
});
8989

9090
this._leavingSub = this._host._afterLeavingCenter.subscribe(() => {
91-
this.detach();
91+
if (!this._host.preserveContent) {
92+
this.detach();
93+
}
9294
});
9395
}
9496

@@ -144,6 +146,9 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy {
144146
/** Duration for the tab's animation. */
145147
@Input() animationDuration: string = '500ms';
146148

149+
/** Whether the tab's content should be kept in the DOM while it's off-screen. */
150+
@Input() preserveContent: boolean = false;
151+
147152
/** The shifted index position of the tab body, where zero represents the active center tab. */
148153
@Input()
149154
set position(position: number) {

src/material/tabs/tab-config.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ export interface MatTabsConfig {
2929

3030
/** `tabindex` to be set on the inner element that wraps the tab content. */
3131
contentTabIndex?: number;
32+
33+
/**
34+
* By default tabs remove their content from the DOM while it's off-screen.
35+
* Setting this to `true` will keep it in the DOM which will prevent elements
36+
* like iframes and videos from reloading next time it comes back into the view.
37+
*/
38+
preserveContent?: boolean;
3239
}
3340

3441
/** Injection token that can be used to provide the default options the tabs module. */

src/material/tabs/tab-group.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
[position]="tab.position!"
4848
[origin]="tab.origin"
4949
[animationDuration]="animationDuration"
50+
[preserveContent]="preserveContent"
5051
(_onCentered)="_removeTabBodyWrapperHeight()"
5152
(_onCentering)="_setTabBodyWrapperHeight($event)">
5253
</mat-tab-body>

src/material/tabs/tab-group.spec.ts

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -642,6 +642,44 @@ describe('MatTabGroup', () => {
642642

643643
expect(tabGroupNode.classList).toContain('mat-tab-group-inverted-header');
644644
});
645+
646+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
647+
fixture.componentInstance.preserveContent = true;
648+
fixture.detectChanges();
649+
650+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
651+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
652+
653+
tabGroup.selectedIndex = 3;
654+
fixture.detectChanges();
655+
tick();
656+
657+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
658+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
659+
}));
660+
661+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
662+
const contentElements: HTMLElement[] =
663+
Array.from(fixture.nativeElement.querySelectorAll('.mat-tab-body-content'));
664+
665+
expect(contentElements.map(element => element.style.visibility))
666+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
667+
668+
tabGroup.selectedIndex = 2;
669+
fixture.detectChanges();
670+
tick();
671+
672+
expect(contentElements.map(element => element.style.visibility))
673+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
674+
675+
tabGroup.selectedIndex = 1;
676+
fixture.detectChanges();
677+
tick();
678+
679+
expect(contentElements.map(element => element.style.visibility))
680+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
681+
}));
682+
645683
});
646684

647685
describe('lazy loaded tabs', () => {
@@ -975,7 +1013,7 @@ class AsyncTabsTestApp implements OnInit {
9751013

9761014
@Component({
9771015
template: `
978-
<mat-tab-group>
1016+
<mat-tab-group [preserveContent]="preserveContent">
9791017
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
9801018
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
9811019
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -984,6 +1022,7 @@ class AsyncTabsTestApp implements OnInit {
9841022
`
9851023
})
9861024
class TabGroupWithSimpleApi {
1025+
preserveContent = false;
9871026
otherLabel = 'Fruit';
9881027
otherContent = 'Apples, grapes';
9891028
@ViewChild('legumes') legumes: any;

src/material/tabs/tab-group.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,14 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
147147
@Input()
148148
disablePagination: boolean;
149149

150+
/**
151+
* By default tabs remove their content from the DOM while it's off-screen.
152+
* Setting this to `true` will keep it in the DOM which will prevent elements
153+
* like iframes and videos from reloading next time it comes back into the view.
154+
*/
155+
@Input()
156+
preserveContent: boolean;
157+
150158
/** Background color of the tab group. */
151159
@Input()
152160
get backgroundColor(): ThemePalette { return this._backgroundColor; }
@@ -192,6 +200,7 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
192200
this.dynamicHeight = defaultConfig && defaultConfig.dynamicHeight != null ?
193201
defaultConfig.dynamicHeight : false;
194202
this.contentTabIndex = defaultConfig?.contentTabIndex ?? null;
203+
this.preserveContent = !!defaultConfig?.preserveContent;
195204
}
196205

197206
/**

src/material/tabs/tabs-animations.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,39 @@ export const matTabsAnimations: {
2323
} = {
2424
/** Animation translates a tab along the X axis. */
2525
translateTab: trigger('translateTab', [
26-
// Note: transitions to `none` instead of 0, because some browsers might blur the content.
27-
state('center, void, left-origin-center, right-origin-center', style({transform: 'none'})),
26+
state('center, void, left-origin-center, right-origin-center', style({
27+
// Transitions to `none` instead of 0, because some browsers might blur the content.
28+
transform: 'none',
29+
// Ensures that the `visibility: hidden` from below is cleared.
30+
visibility: 'visible'
31+
})),
2832

2933
// If the tab is either on the left or right, we additionally add a `min-height` of 1px
3034
// in order to ensure that the element has a height before its state changes. This is
3135
// necessary because Chrome does seem to skip the transition in RTL mode if the element does
3236
// not have a static height and is not rendered. See related issue: #9465
33-
state('left', style({transform: 'translate3d(-100%, 0, 0)', minHeight: '1px'})),
34-
state('right', style({transform: 'translate3d(100%, 0, 0)', minHeight: '1px'})),
37+
state('left', style({
38+
transform: 'translate3d(-100%, 0, 0)',
39+
minHeight: '1px',
40+
41+
// Normally this is redundant since we detach the content from the DOM, but if the user
42+
// opted into keeping the content in the DOM, we have to hide it so it isn't focusable.
43+
visibility: 'hidden'
44+
})),
45+
state('right', style({
46+
transform: 'translate3d(100%, 0, 0)',
47+
minHeight: '1px',
48+
visibility: 'hidden'
49+
})),
3550

3651
transition('* => left, * => right, left => center, right => center',
3752
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')),
3853
transition('void => left-origin-center', [
39-
style({transform: 'translate3d(-100%, 0, 0)'}),
54+
style({transform: 'translate3d(-100%, 0, 0)', visibility: 'hidden'}),
4055
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')
4156
]),
4257
transition('void => right-origin-center', [
43-
style({transform: 'translate3d(100%, 0, 0)'}),
58+
style({transform: 'translate3d(100%, 0, 0)', visibility: 'hidden'}),
4459
animate('{{animationDuration}} cubic-bezier(0.35, 0, 0.25, 1)')
4560
])
4661
])

src/material/tabs/tabs.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,15 @@ duration can be configured globally using the `MAT_TABS_CONFIG` injection token.
8484
"file": "tab-group-animations-example.html",
8585
"region": "slow-animation-duration"}) -->
8686

87+
### Keeping the tab content inside the DOM while it's off-screen
88+
By default the `<mat-tab-group>` will remove the content of off-screen tabs from the DOM until they
89+
come into the view. This is optimal for most cases since it keeps the DOM size smaller, but it
90+
isn't great for others like when a tab has an `<audio>` or `<video>` element, because the content
91+
will be re-initialized whenever the user navigates to the tab. If you want to keep the content of
92+
off-screen tabs in the DOM, you can set the `preserveContent` input to `true`.
93+
94+
<!-- example(tab-group-preserve-content) -->
95+
8796
### Accessibility
8897
`<mat-tab-group>` and `<mat-nav-tab-bar>` use different interaction patterns. The
8998
`<mat-tab-group>` component combines `tablist`, `tab`, and `tabpanel` into a single component with

tools/public_api_guard/material/tabs.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,10 @@ export abstract class _MatTabBodyBase implements OnInit, OnDestroy {
158158
abstract _portalHost: CdkPortalOutlet;
159159
set position(position: number);
160160
_position: MatTabBodyPositionState;
161+
preserveContent: boolean;
161162
readonly _translateTabComplete: Subject<AnimationEvent_2>;
162163
// (undocumented)
163-
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabBodyBase, never, never, { "_content": "content"; "origin": "origin"; "animationDuration": "animationDuration"; "position": "position"; }, { "_onCentering": "_onCentering"; "_beforeCentering": "_beforeCentering"; "_afterLeavingCenter": "_afterLeavingCenter"; "_onCentered": "_onCentered"; }, never>;
164+
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabBodyBase, never, never, { "_content": "content"; "origin": "origin"; "animationDuration": "animationDuration"; "preserveContent": "preserveContent"; "position": "position"; }, { "_onCentering": "_onCentering"; "_beforeCentering": "_beforeCentering"; "_afterLeavingCenter": "_afterLeavingCenter"; "_onCentered": "_onCentered"; }, never>;
164165
// (undocumented)
165166
static ɵfac: i0.ɵɵFactoryDeclaration<_MatTabBodyBase, [null, { optional: true; }, null]>;
166167
}
@@ -256,6 +257,7 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
256257
ngAfterContentInit(): void;
257258
// (undocumented)
258259
ngOnDestroy(): void;
260+
preserveContent: boolean;
259261
realignInkBar(): void;
260262
_removeTabBodyWrapperHeight(): void;
261263
get selectedIndex(): number | null;
@@ -270,7 +272,7 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
270272
abstract _tabHeader: MatTabGroupBaseHeader;
271273
_tabs: QueryList<MatTab>;
272274
// (undocumented)
273-
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabGroupBase, never, never, { "dynamicHeight": "dynamicHeight"; "selectedIndex": "selectedIndex"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; "contentTabIndex": "contentTabIndex"; "disablePagination": "disablePagination"; "backgroundColor": "backgroundColor"; }, { "selectedIndexChange": "selectedIndexChange"; "focusChange": "focusChange"; "animationDone": "animationDone"; "selectedTabChange": "selectedTabChange"; }, never>;
275+
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabGroupBase, never, never, { "dynamicHeight": "dynamicHeight"; "selectedIndex": "selectedIndex"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; "contentTabIndex": "contentTabIndex"; "disablePagination": "disablePagination"; "preserveContent": "preserveContent"; "backgroundColor": "backgroundColor"; }, { "selectedIndexChange": "selectedIndexChange"; "focusChange": "focusChange"; "animationDone": "animationDone"; "selectedTabChange": "selectedTabChange"; }, never>;
274276
// (undocumented)
275277
static ɵfac: i0.ɵɵFactoryDeclaration<_MatTabGroupBase, [null, null, { optional: true; }, { optional: true; }]>;
276278
}
@@ -439,6 +441,7 @@ export interface MatTabsConfig {
439441
disablePagination?: boolean;
440442
dynamicHeight?: boolean;
441443
fitInkBarToContent?: boolean;
444+
preserveContent?: boolean;
442445
}
443446

444447
// @public (undocumented)

0 commit comments

Comments
 (0)