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.
This commit is contained in:
Kristiyan Kostadinov
2018-07-11 17:03:37 +02:00
committed by Jeremy Elbourn
parent 6a472eb6a7
commit 0186a039a3
2 changed files with 18 additions and 1 deletions
+14
View File
@@ -403,6 +403,20 @@ describe('MatTabGroup', () => {
expect(component._tabs.toArray()[1].isActive).toBe(true);
});
it('should not fire `selectedTabChange` when the amount of tabs changes', fakeAsync(() => {
fixture.detectChanges();
fixture.componentInstance.selectedIndex = 1;
fixture.detectChanges();
// Add a new tab at the beginning.
spyOn(fixture.componentInstance, 'handleSelection');
fixture.componentInstance.tabs.unshift({label: 'New tab', content: 'at the start'});
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(fixture.componentInstance.handleSelection).not.toHaveBeenCalled();
}));
});
+4 -1
View File
@@ -205,7 +205,10 @@ export class MatTabGroup extends _MatTabGroupMixinBase implements AfterContentIn
// Maintain the previously-selected tab if a new tab is added or removed.
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].isActive) {
this._indexToSelect = i;
// Assign both to the `_indexToSelect` and `_selectedIndex` so we don't fire a changed
// event, otherwise the consumer may end up in an infinite loop in some edge cases like
// adding a tab within the `selectedIndexChange` event.
this._indexToSelect = this._selectedIndex = i;
break;
}
}