Skip to content

Commit 93e9415

Browse files
crisbetojelbourn
authored andcommitted
fix(tabs): tab nav bar not highlighting active tab if rendered after init (#16624)
Fixes the `mat-tab-nav-bar` not aligning the ink bar to the active item, if the list of items comes in after the bar has been rendered. Fixes #16607.
1 parent 792e886 commit 93e9415

File tree

3 files changed

+24
-2
lines changed

3 files changed

+24
-2
lines changed

src/material/tabs/paginated-tab-header.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export abstract class MatPaginatedTabHeader implements AfterContentChecked, Afte
8080
private _selectedIndexChanged = false;
8181

8282
/** Emits when the component is destroyed. */
83-
private readonly _destroyed = new Subject<void>();
83+
protected readonly _destroyed = new Subject<void>();
8484

8585
/** Whether the controls for pagination should be displayed */
8686
_showPaginationControls = false;

src/material/tabs/tab-nav-bar/tab-nav-bar.spec.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,22 @@ describe('MatTabNavBar', () => {
253253
expect(tabLink.tabIndex).toBe(3, 'Expected the tabIndex to be have been set to 3.');
254254
});
255255

256+
it('should select the proper tab, if the tabs come in after init', () => {
257+
const fixture = TestBed.createComponent(SimpleTabNavBarTestApp);
258+
const instance = fixture.componentInstance;
259+
260+
instance.tabs = [];
261+
instance.activeIndex = 1;
262+
fixture.detectChanges();
263+
264+
expect(instance.tabNavBar.selectedIndex).toBe(-1);
265+
266+
instance.tabs = [0, 1, 2];
267+
fixture.detectChanges();
268+
269+
expect(instance.tabNavBar.selectedIndex).toBe(1);
270+
});
271+
256272
describe('ripples', () => {
257273
let fixture: ComponentFixture<SimpleTabNavBarTestApp>;
258274

src/material/tabs/tab-nav-bar/tab-nav-bar.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import {FocusMonitor, FocusableOption} from '@angular/cdk/a11y';
4646
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
4747
import {MatInkBar} from '../ink-bar';
4848
import {MatPaginatedTabHeader} from '../paginated-tab-header';
49+
import {startWith, takeUntil} from 'rxjs/operators';
4950

5051

5152
/**
@@ -123,7 +124,12 @@ export class MatTabNav extends MatPaginatedTabHeader implements AfterContentChec
123124
}
124125

125126
ngAfterContentInit() {
126-
this.updateActiveLink();
127+
// We need this to run before the `changes` subscription in parent to ensure that the
128+
// selectedIndex is up-to-date by the time the super class starts looking for it.
129+
this._items.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
130+
this.updateActiveLink();
131+
});
132+
127133
super.ngAfterContentInit();
128134
}
129135

0 commit comments

Comments
 (0)