Skip to content

Commit 0186a03

Browse files
crisbetojelbourn
authored andcommitted
fix(tabs): don't fire change event when amount of tabs changes (#12097)
Fixes the tab group firing its `selectedTabChange` event when the amount of tabs changes, which might throw the consumer into an infinite loop if they're adding new tabs inside the callback. Fixes #12084.
1 parent 6a472eb commit 0186a03

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,20 @@ describe('MatTabGroup', () => {
403403
expect(component._tabs.toArray()[1].isActive).toBe(true);
404404
});
405405

406+
it('should not fire `selectedTabChange` when the amount of tabs changes', fakeAsync(() => {
407+
fixture.detectChanges();
408+
fixture.componentInstance.selectedIndex = 1;
409+
fixture.detectChanges();
410+
411+
// Add a new tab at the beginning.
412+
spyOn(fixture.componentInstance, 'handleSelection');
413+
fixture.componentInstance.tabs.unshift({label: 'New tab', content: 'at the start'});
414+
fixture.detectChanges();
415+
tick();
416+
fixture.detectChanges();
417+
418+
expect(fixture.componentInstance.handleSelection).not.toHaveBeenCalled();
419+
}));
406420

407421
});
408422

src/lib/tabs/tab-group.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,10 @@ export class MatTabGroup extends _MatTabGroupMixinBase implements AfterContentIn
205205
// Maintain the previously-selected tab if a new tab is added or removed.
206206
for (let i = 0; i < tabs.length; i++) {
207207
if (tabs[i].isActive) {
208-
this._indexToSelect = i;
208+
// Assign both to the `_indexToSelect` and `_selectedIndex` so we don't fire a changed
209+
// event, otherwise the consumer may end up in an infinite loop in some edge cases like
210+
// adding a tab within the `selectedIndexChange` event.
211+
this._indexToSelect = this._selectedIndex = i;
209212
break;
210213
}
211214
}

0 commit comments

Comments
 (0)