Skip to content

Commit 75bdbe5

Browse files
committed
fix(select): optionSelectionChanges not emitting when the list of options changes
Along the same lines as #14813. Fixes `MatSelect.optionSelectionChanges` not emitting if the list options changes.
1 parent 58254ae commit 75bdbe5

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/lib/select/select.spec.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1462,6 +1462,36 @@ describe('MatSelect', () => {
14621462
subscription!.unsubscribe();
14631463
}));
14641464

1465+
it('should emit to `optionSelectionChanges` after the list of options has changed',
1466+
fakeAsync(() => {
1467+
let spy = jasmine.createSpy('option selection spy');
1468+
let subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy);
1469+
let selectFirstOption = () => {
1470+
trigger.click();
1471+
fixture.detectChanges();
1472+
flush();
1473+
1474+
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
1475+
option.click();
1476+
fixture.detectChanges();
1477+
flush();
1478+
};
1479+
1480+
fixture.componentInstance.foods = [{value: 'salad-8', viewValue: 'Salad'}];
1481+
fixture.detectChanges();
1482+
selectFirstOption();
1483+
1484+
expect(spy).toHaveBeenCalledTimes(1);
1485+
1486+
fixture.componentInstance.foods = [{value: 'fruit-9', viewValue: 'Fruit'}];
1487+
fixture.detectChanges();
1488+
selectFirstOption();
1489+
1490+
expect(spy).toHaveBeenCalledTimes(2);
1491+
1492+
subscription!.unsubscribe();
1493+
}));
1494+
14651495
});
14661496

14671497
describe('forms integration', () => {

src/lib/select/select.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -442,8 +442,13 @@ export class MatSelect extends _MatSelectMixinBase implements AfterContentInit,
442442

443443
/** Combined stream of all of the child options' change events. */
444444
readonly optionSelectionChanges: Observable<MatOptionSelectionChange> = defer(() => {
445-
if (this.options) {
446-
return merge(...this.options.map(option => option.onSelectionChange));
445+
const options = this.options;
446+
447+
if (options) {
448+
return options.changes.pipe(
449+
startWith(options),
450+
switchMap(() => merge(...options.map(option => option.onSelectionChange)))
451+
);
447452
}
448453

449454
return this._ngZone.onStable

0 commit comments

Comments
 (0)