Skip to content

Commit 743aed8

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 f7d7502 commit 743aed8

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
@@ -18,6 +18,9 @@ import {
1818
import {TabGroupDynamicExample} from './tab-group-dynamic/tab-group-dynamic-example';
1919
import {TabGroupHeaderBelowExample} from './tab-group-header-below/tab-group-header-below-example';
2020
import {TabGroupLazyLoadedExample} from './tab-group-lazy-loaded/tab-group-lazy-loaded-example';
21+
import {
22+
TabGroupPreserveContentExample
23+
} from './tab-group-preserve-content/tab-group-preserve-content-example';
2124
import {TabGroupStretchedExample} from './tab-group-stretched/tab-group-stretched-example';
2225
import {TabGroupThemeExample} from './tab-group-theme/tab-group-theme-example';
2326
import {TabNavBarBasicExample} from './tab-nav-bar-basic/tab-nav-bar-basic-example';
@@ -35,6 +38,7 @@ export {
3538
TabGroupStretchedExample,
3639
TabGroupThemeExample,
3740
TabNavBarBasicExample,
41+
TabGroupPreserveContentExample,
3842
};
3943

4044
const EXAMPLES = [
@@ -50,6 +54,7 @@ const EXAMPLES = [
5054
TabGroupStretchedExample,
5155
TabGroupThemeExample,
5256
TabNavBarBasicExample,
57+
TabGroupPreserveContentExample,
5358
];
5459

5560
@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
@@ -59,6 +59,7 @@
5959
[position]="tab.position!"
6060
[origin]="tab.origin"
6161
[animationDuration]="animationDuration"
62+
[preserveContent]="preserveContent"
6263
(_onCentered)="_removeTabBodyWrapperHeight()"
6364
(_onCentering)="_setTabBodyWrapperHeight($event)">
6465
</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
@@ -578,6 +578,44 @@ describe('MDC-based MatTabGroup', () => {
578578

579579
expect(tabGroupNode.classList).toContain('mat-mdc-tab-group-inverted-header');
580580
});
581+
582+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
583+
fixture.componentInstance.preserveContent = true;
584+
fixture.detectChanges();
585+
586+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
587+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
588+
589+
tabGroup.selectedIndex = 3;
590+
fixture.detectChanges();
591+
tick();
592+
593+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
594+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
595+
}));
596+
597+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
598+
const contentElements: HTMLElement[] =
599+
Array.from(fixture.nativeElement.querySelectorAll('.mat-mdc-tab-body-content'));
600+
601+
expect(contentElements.map(element => element.style.visibility))
602+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
603+
604+
tabGroup.selectedIndex = 2;
605+
fixture.detectChanges();
606+
tick();
607+
608+
expect(contentElements.map(element => element.style.visibility))
609+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
610+
611+
tabGroup.selectedIndex = 1;
612+
fixture.detectChanges();
613+
tick();
614+
615+
expect(contentElements.map(element => element.style.visibility))
616+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
617+
}));
618+
581619
});
582620

583621
describe('lazy loaded tabs', () => {
@@ -924,7 +962,7 @@ class AsyncTabsTestApp implements OnInit {
924962

925963
@Component({
926964
template: `
927-
<mat-tab-group>
965+
<mat-tab-group [preserveContent]="preserveContent">
928966
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
929967
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
930968
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -933,6 +971,7 @@ class AsyncTabsTestApp implements OnInit {
933971
`
934972
})
935973
class TabGroupWithSimpleApi {
974+
preserveContent = false;
936975
otherLabel = 'Fruit';
937976
otherContent = 'Apples, grapes';
938977
@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
@@ -45,6 +45,7 @@
4545
[position]="tab.position!"
4646
[origin]="tab.origin"
4747
[animationDuration]="animationDuration"
48+
[preserveContent]="preserveContent"
4849
(_onCentered)="_removeTabBodyWrapperHeight()"
4950
(_onCentering)="_setTabBodyWrapperHeight($event)">
5051
</mat-tab-body>

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

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

577577
expect(tabGroupNode.classList).toContain('mat-tab-group-inverted-header');
578578
});
579+
580+
it('should be able to opt into keeping the inactive tab content in the DOM', fakeAsync(() => {
581+
fixture.componentInstance.preserveContent = true;
582+
fixture.detectChanges();
583+
584+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
585+
expect(fixture.nativeElement.textContent).not.toContain('Peanuts');
586+
587+
tabGroup.selectedIndex = 3;
588+
fixture.detectChanges();
589+
tick();
590+
591+
expect(fixture.nativeElement.textContent).toContain('Pizza, fries');
592+
expect(fixture.nativeElement.textContent).toContain('Peanuts');
593+
}));
594+
595+
it('should visibly hide the content of inactive tabs', fakeAsync(() => {
596+
const contentElements: HTMLElement[] =
597+
Array.from(fixture.nativeElement.querySelectorAll('.mat-tab-body-content'));
598+
599+
expect(contentElements.map(element => element.style.visibility))
600+
.toEqual(['visible', 'hidden', 'hidden', 'hidden']);
601+
602+
tabGroup.selectedIndex = 2;
603+
fixture.detectChanges();
604+
tick();
605+
606+
expect(contentElements.map(element => element.style.visibility))
607+
.toEqual(['hidden', 'hidden', 'visible', 'hidden']);
608+
609+
tabGroup.selectedIndex = 1;
610+
fixture.detectChanges();
611+
tick();
612+
613+
expect(contentElements.map(element => element.style.visibility))
614+
.toEqual(['hidden', 'visible', 'hidden', 'hidden']);
615+
}));
616+
579617
});
580618

581619
describe('lazy loaded tabs', () => {
@@ -867,7 +905,7 @@ class AsyncTabsTestApp implements OnInit {
867905

868906
@Component({
869907
template: `
870-
<mat-tab-group>
908+
<mat-tab-group [preserveContent]="preserveContent">
871909
<mat-tab label="Junk food"> Pizza, fries </mat-tab>
872910
<mat-tab label="Vegetables"> Broccoli, spinach </mat-tab>
873911
<mat-tab [label]="otherLabel"> {{otherContent}} </mat-tab>
@@ -876,6 +914,7 @@ class AsyncTabsTestApp implements OnInit {
876914
`
877915
})
878916
class TabGroupWithSimpleApi {
917+
preserveContent = false;
879918
otherLabel = 'Fruit';
880919
otherContent = 'Apples, grapes';
881920
@ViewChild('legumes') legumes: any;

src/material/tabs/tab-group.ts

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

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

186195
/**

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.ɵɵDirectiveDefWithMeta<_MatTabBodyBase, never, never, { "_content": "content"; "origin": "origin"; "animationDuration": "animationDuration"; "position": "position"; }, { "_onCentering": "_onCentering"; "_beforeCentering": "_beforeCentering"; "_afterLeavingCenter": "_afterLeavingCenter"; "_onCentered": "_onCentered"; }, never>;
29+
static ɵdir: i0.ɵɵDirectiveDefWithMeta<_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.ɵɵFactoryDef<_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>;
@@ -66,7 +68,7 @@ export declare abstract class _MatTabGroupBase extends _MatTabGroupMixinBase imp
6668
static ngAcceptInputType_disableRipple: BooleanInput;
6769
static ngAcceptInputType_dynamicHeight: BooleanInput;
6870
static ngAcceptInputType_selectedIndex: NumberInput;
69-
static ɵdir: i0.ɵɵDirectiveDefWithMeta<_MatTabGroupBase, never, never, { "dynamicHeight": "dynamicHeight"; "selectedIndex": "selectedIndex"; "headerPosition": "headerPosition"; "animationDuration": "animationDuration"; "disablePagination": "disablePagination"; "backgroundColor": "backgroundColor"; }, { "selectedIndexChange": "selectedIndexChange"; "focusChange": "focusChange"; "animationDone": "animationDone"; "selectedTabChange": "selectedTabChange"; }, never>;
71+
static ɵdir: i0.ɵɵDirectiveDefWithMeta<_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>;
7072
static ɵfac: i0.ɵɵFactoryDef<_MatTabGroupBase, [null, null, { optional: true; }, { optional: true; }]>;
7173
}
7274

@@ -252,6 +254,7 @@ export interface MatTabsConfig {
252254
disablePagination?: boolean;
253255
dynamicHeight?: boolean;
254256
fitInkBarToContent?: boolean;
257+
preserveContent?: boolean;
255258
}
256259

257260
export declare class MatTabsModule {

0 commit comments

Comments
 (0)