Skip to content

Commit 51eee12

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 119684e commit 51eee12

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
@@ -60,6 +60,7 @@
6060
[position]="tab.position!"
6161
[origin]="tab.origin"
6262
[animationDuration]="animationDuration"
63+
[preserveContent]="preserveContent"
6364
(_onCentered)="_removeTabBodyWrapperHeight()"
6465
(_onCentering)="_setTabBodyWrapperHeight($event)">
6566
</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
@@ -627,6 +627,44 @@ describe('MDC-based MatTabGroup', () => {
627627

628628
expect(tabGroupNode.classList).toContain('mat-mdc-tab-group-inverted-header');
629629
});
630+
631+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
632+
fixture.componentInstance.preserveContent = true;
633+
fixture.detectChanges();
634+
635+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
636+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
637+
638+
tabGroup.selectedIndex = 3;
639+
fixture.detectChanges();
640+
tick();
641+
642+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
643+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
644+
}));
645+
646+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
647+
const contentElements: HTMLElement[] =
648+
Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab-body-content'));
649+
650+
expect(contentElements.map(element => element.style.visibility))
651+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
652+
653+
tabGroup.selectedIndex = 2;
654+
fixture.detectChanges();
655+
tick();
656+
657+
expect(contentElements.map(element => element.style.visibility))
658+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
659+
660+
tabGroup.selectedIndex = 1;
661+
fixture.detectChanges();
662+
tick();
663+
664+
expect(contentElements.map(element => element.style.visibility))
665+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
666+
}));
667+
630668
});
631669

632670
describe('lazy loaded tabs', () => {
@@ -973,7 +1011,7 @@ class AsyncTabsTestApp implements OnInit {
9731011

9741012
@Component({
9751013
template: `
976-
<mat-tab-group>
1014+
<mat-tab-group [preserveContent]="preserveContent">
9771015
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
9781016
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
9791017
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -982,6 +1020,7 @@ class AsyncTabsTestApp implements OnInit {
9821020
`
9831021
})
9841022
class TabGroupWithSimpleApi {
1023+
preserveContent = false;
9851024
otherLabel = 'Fruit';
9861025
otherContent = 'Apples, grapes';
9871026
@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
@@ -26,6 +26,13 @@ export interface MatTabsConfig {
2626

2727
/** Whether the tab group should grow to the size of the active tab. */
2828
dynamicHeight?: boolean;
29+
30+
/**
31+
* By default tabs remove their content from the DOM while it's off-screen.
32+
* Setting this to `true` will keep it in the DOM which will prevent elements
33+
* like iframes and videos from reloading next time it comes back into the view.
34+
*/
35+
preserveContent?: boolean;
2936
}
3037

3138
/** 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
@@ -46,6 +46,7 @@
4646
[position]="tab.position!"
4747
[origin]="tab.origin"
4848
[animationDuration]="animationDuration"
49+
[preserveContent]="preserveContent"
4950
(_onCentered)="_removeTabBodyWrapperHeight()"
5051
(_onCentering)="_setTabBodyWrapperHeight($event)">
5152
</mat-tab-body>

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

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

627627
expect(tabGroupNode.classList).toContain('mat-tab-group-inverted-header');
628628
});
629+
630+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
631+
fixture.componentInstance.preserveContent = true;
632+
fixture.detectChanges();
633+
634+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
635+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
636+
637+
tabGroup.selectedIndex = 3;
638+
fixture.detectChanges();
639+
tick();
640+
641+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
642+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
643+
}));
644+
645+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
646+
const contentElements: HTMLElement[] =
647+
Array.from(fixture.nativeElement.querySelectorAll('.mat-tab-body-content'));
648+
649+
expect(contentElements.map(element => element.style.visibility))
650+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
651+
652+
tabGroup.selectedIndex = 2;
653+
fixture.detectChanges();
654+
tick();
655+
656+
expect(contentElements.map(element => element.style.visibility))
657+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
658+
659+
tabGroup.selectedIndex = 1;
660+
fixture.detectChanges();
661+
tick();
662+
663+
expect(contentElements.map(element => element.style.visibility))
664+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
665+
}));
666+
629667
});
630668

631669
describe('lazy loaded tabs', () => {
@@ -917,7 +955,7 @@ class AsyncTabsTestApp implements OnInit {
917955

918956
@Component({
919957
template: `
920-
<mat-tab-group>
958+
<mat-tab-group [preserveContent]="preserveContent">
921959
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
922960
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
923961
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -926,6 +964,7 @@ class AsyncTabsTestApp implements OnInit {
926964
`
927965
})
928966
class TabGroupWithSimpleApi {
967+
preserveContent = false;
929968
otherLabel = 'Fruit';
930969
otherContent = 'Apples, grapes';
931970
@ViewChild('legumes') legumes: any;

src/material/tabs/tab-group.ts

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

141+
/**
142+
* By default tabs remove their content from the DOM while it's off-screen.
143+
* Setting this to `true` will keep it in the DOM which will prevent elements
144+
* like iframes and videos from reloading next time it comes back into the view.
145+
*/
146+
@Input()
147+
preserveContent: boolean;
148+
141149
/** Background color of the tab group. */
142150
@Input()
143151
get backgroundColor(): ThemePalette { return this._backgroundColor; }
@@ -182,6 +190,7 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
182190
defaultConfig.disablePagination : false;
183191
this.dynamicHeight = defaultConfig && defaultConfig.dynamicHeight != null ?
184192
defaultConfig.dynamicHeight : false;
193+
this.preserveContent = !!defaultConfig?.preserveContent;
185194
}
186195

187196
/**

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.d.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,14 @@ export declare abstract class _MatTabBodyBase implements OnInit, OnDestroy {
1919
animationDuration: string;
2020
origin: number | null;
2121
set position(position: number);
22+
preserveContent: boolean;
2223
constructor(_elementRef: ElementRef<HTMLElement>, _dir: Directionality, changeDetectorRef: ChangeDetectorRef);
2324
_getLayoutDirection(): Direction;
2425
_isCenterPosition(position: MatTabBodyPositionState | string): boolean;
2526
_onTranslateTabStarted(event: AnimationEvent): void;
2627
ngOnDestroy(): void;
2728
ngOnInit(): void;
28-
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabBodyBase, never, never, { "_content": "content"; "origin": "origin"; "animationDuration": "animationDuration"; "position": "position"; }, { "_onCentering": "_onCentering"; "_beforeCentering": "_beforeCentering"; "_afterLeavingCenter": "_afterLeavingCenter"; "_onCentered": "_onCentered"; }, never>;
29+
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>;
2930
static ɵfac: i0.ɵɵFactoryDeclaration<_MatTabBodyBase, [null, { optional: true; }, null]>;
3031
}
3132

@@ -46,6 +47,7 @@ export declare abstract class _MatTabGroupBase extends _MatTabGroupMixinBase imp
4647
set dynamicHeight(value: boolean);
4748
readonly focusChange: EventEmitter<MatTabChangeEvent>;
4849
headerPosition: MatTabHeaderPosition;
50+
preserveContent: boolean;
4951
get selectedIndex(): number | null;
5052
set selectedIndex(value: number | null);
5153
readonly selectedIndexChange: EventEmitter<number>;
@@ -68,7 +70,7 @@ export declare abstract class _MatTabGroupBase extends _MatTabGroupMixinBase imp
6870
static ngAcceptInputType_disableRipple: BooleanInput;
6971
static ngAcceptInputType_dynamicHeight: BooleanInput;
7072
static ngAcceptInputType_selectedIndex: NumberInput;
71-
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabGroupBase, never, never, { "dynamicHeight": "dynamicHeight"; "selectedIndex": "selectedIndex"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; "disablePagination": "disablePagination"; "backgroundColor": "backgroundColor"; }, { "selectedIndexChange": "selectedIndexChange"; "focusChange": "focusChange"; "animationDone": "animationDone"; "selectedTabChange": "selectedTabChange"; }, never>;
73+
static ɵdir: i0.ɵɵDirectiveDeclaration<_MatTabGroupBase, never, never, { "dynamicHeight": "dynamicHeight"; "selectedIndex": "selectedIndex"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; "disablePagination": "disablePagination"; "preserveContent": "preserveContent"; "backgroundColor": "backgroundColor"; }, { "selectedIndexChange": "selectedIndexChange"; "focusChange": "focusChange"; "animationDone": "animationDone"; "selectedTabChange": "selectedTabChange"; }, never>;
7274
static ɵfac: i0.ɵɵFactoryDeclaration<_MatTabGroupBase, [null, null, { optional: true; }, { optional: true; }]>;
7375
}
7476

@@ -254,6 +256,7 @@ export interface MatTabsConfig {
254256
disablePagination?: boolean;
255257
dynamicHeight?: boolean;
256258
fitInkBarToContent?: boolean;
259+
preserveContent?: boolean;
257260
}
258261

259262
export declare class MatTabsModule {

0 commit comments

Comments
 (0)