Skip to content

Commit

Permalink
feat(restoring selections): update restoration logic to ignore filter…
Browse files Browse the repository at this point in the history
…ing in progress when alwaysRestoreSelectedOptionsMulti = false
  • Loading branch information
Jamie McInerney committed Mar 28, 2022
1 parent 6dfac64 commit 1378ffb
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions src/app/mat-select-search/mat-select-search.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -573,37 +573,50 @@ export class MatSelectSearchComponent implements OnInit, OnDestroy, ControlValue
}
return;
}

// if <mat-select [multiple]="true">
// store previously selected values and restore them when they are deselected
// because the option is not available while we are currently filtering
this.previousSelectedValues = this.matSelect.ngControl.value;

this.matSelect.ngControl.valueChanges
.pipe(takeUntil(this._onDestroy))
.subscribe((values) => {
.subscribe((currentSelectedValues) => {
if (!this.matSelect.multiple) {
this.previousSelectedValues = currentSelectedValues;
return;
}

if (!this.alwaysRestoreSelectedOptionsMulti) {
this.previousSelectedValues = currentSelectedValues;
return;
}

const filteringInProgress = (this._formControl.value && this._formControl.value.length);

let restoreSelectedValues = false;
if (this.matSelect.multiple) {
if ((this.alwaysRestoreSelectedOptionsMulti || (this._formControl.value && this._formControl.value.length))
&& this.previousSelectedValues && Array.isArray(this.previousSelectedValues)) {
if (!values || !Array.isArray(values)) {
values = [];

if (filteringInProgress && this.previousSelectedValues && Array.isArray(this.previousSelectedValues)) {
if (!currentSelectedValues || !Array.isArray(currentSelectedValues)) {
currentSelectedValues = [];
}

const optionValues = this.matSelect.options.map(option => option.value);

this.previousSelectedValues.forEach(previousValue => {
if (!values.some(v => this.matSelect.compareWith(v, previousValue))
&& !optionValues.some(v => this.matSelect.compareWith(v, previousValue))) {
// if a value that was selected before is deselected and not found in the options, it was deselected
// due to the filtering, so we restore it.
values.push(previousValue);
restoreSelectedValues = true;
}
const previousValueDeselectedDuringFiltering = !currentSelectedValues.some(v => this.matSelect.compareWith(v, previousValue)) && !optionValues.some(v => this.matSelect.compareWith(v, previousValue));

if (previousValueDeselectedDuringFiltering) {
currentSelectedValues.push(previousValue);
restoreSelectedValues = true;
}
});
}
}
this.previousSelectedValues = values;

this.previousSelectedValues = currentSelectedValues;

if (restoreSelectedValues) {
this.matSelect._onChange(values);
this.matSelect._onChange(currentSelectedValues);
}
});
}
Expand Down

0 comments on commit 1378ffb

Please sign in to comment.