Skip to content

Commit

Permalink
fix(selection-list): options not marked as selected if value is assig…
Browse files Browse the repository at this point in the history
…ned too early (#9090)

Fixes the selection list options not being marked as selected if the component's value is set before `ngAfterContentInit`.

Fixes #9085.
  • Loading branch information
crisbeto authored and jelbourn committed Jan 9, 2018
1 parent 6ef0401 commit 38481c6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/lib/list/selection-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,22 @@ describe('MatSelectionList with forms', () => {
expect(listOptions.every(option => !option.selected))
.toBe(true, 'Expected every list option to be unselected.');
});

it('should mark options as selected when the value is set before they are initialized', () => {
fixture.destroy();
fixture = TestBed.createComponent(SelectionListWithFormControl);
selectionListDebug = fixture.debugElement.query(By.directive(MatSelectionList));
selectionList = selectionListDebug.componentInstance;

fixture.componentInstance.formControl.setValue(['opt2', 'opt3']);
fixture.detectChanges();

listOptions = fixture.debugElement.queryAll(By.directive(MatListOption))
.map(optionDebugEl => optionDebugEl.componentInstance);

expect(listOptions[1].selected).toBe(true, 'Expected second option to be selected.');
expect(listOptions[2].selected).toBe(true, 'Expected third option to be selected.');
});
});
});

Expand Down
10 changes: 10 additions & 0 deletions src/lib/list/selection-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,9 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements Focu
/** View to model callback that should be called whenever the selected options change. */
private _onChange: (value: any) => void = (_: any) => {};

/** Used for storing the values that were assigned before the options were initialized. */
private _tempValues: string[]|null;

/** View to model callback that should be called if the list or its options lost focus. */
onTouched: () => void = () => {};

Expand All @@ -301,6 +304,11 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements Focu

ngAfterContentInit(): void {
this._keyManager = new FocusKeyManager<MatListOption>(this.options).withWrap();

if (this._tempValues) {
this._setOptionsFromValues(this._tempValues);
this._tempValues = null;
}
}

/** Focus the selection-list. */
Expand Down Expand Up @@ -369,6 +377,8 @@ export class MatSelectionList extends _MatSelectionListMixinBase implements Focu
writeValue(values: string[]): void {
if (this.options) {
this._setOptionsFromValues(values || []);
} else {
this._tempValues = values;
}
}

Expand Down

0 comments on commit 38481c6

Please sign in to comment.