Skip to content

feat:(angular/component): Configurable reversion value for requireSelection for MatAutocomplete #31141

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.example-form {
min-width: 150px;
max-width: 500px;
width: 100%;
margin-top: 16px;
}

.example-full-width {
width: 100%;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Control value: {{myControl.value || 'empty'}}

<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Number</mat-label>
<input #input
type="text"
placeholder="Pick one"
matInput
[formControl]="myControl"
[matAutocomplete]="auto"
(input)="filter()"
(focus)="filter()">
<mat-autocomplete requireSelection #auto="matAutocomplete" revertToValue="Three">
@for (option of filteredOptions; track option) {
<mat-option [value]="option">{{option}}</mat-option>
}
</mat-autocomplete>
</mat-form-field>
</form>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatInputModule} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';

/**
* @title Revert to a given value instead of null for requireSelection
*/
@Component({
selector: 'autocomplete-revert-to-value-example',
templateUrl: 'autocomplete-revert-to-value-example.html',
styleUrl: 'autocomplete-revert-to-value-example.css',
imports: [
FormsModule,
MatFormFieldModule,
MatInputModule,
MatAutocompleteModule,
ReactiveFormsModule,
],
})
export class AutocompleteRevertToValueExample {
@ViewChild('input') input: ElementRef<HTMLInputElement>;
myControl = new FormControl('');
options: string[] = ['One', 'Two', 'Three', 'Four', 'Five'];
filteredOptions: string[];

constructor() {
this.filteredOptions = this.options.slice();
}

filter(): void {
const filterValue = this.input.nativeElement.value.toLowerCase();
this.filteredOptions = this.options.filter(o => o.toLowerCase().includes(filterValue));
}
}
1 change: 1 addition & 0 deletions src/components-examples/material/autocomplete/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ export {AutocompleteOverviewExample} from './autocomplete-overview/autocomplete-
export {AutocompletePlainInputExample} from './autocomplete-plain-input/autocomplete-plain-input-example';
export {AutocompleteSimpleExample} from './autocomplete-simple/autocomplete-simple-example';
export {AutocompleteRequireSelectionExample} from './autocomplete-require-selection/autocomplete-require-selection-example';
export {AutocompleteRevertToValueExample} from './autocomplete-revert-to-value/autocomplete-revert-to-value-example';
export {AutocompleteHarnessExample} from './autocomplete-harness/autocomplete-harness-example';
1 change: 1 addition & 0 deletions src/dev-app/autocomplete/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ ng_project(
"//src/material/dialog",
"//src/material/form-field",
"//src/material/input",
"//src/material/select",
],
)

Expand Down
33 changes: 31 additions & 2 deletions src/dev-app/autocomplete/autocomplete-demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
[displayWith]="displayFn"
[hideSingleSelectionIndicator]="reactiveHideSingleSelectionIndicator"
[autoActiveFirstOption]="reactiveAutoActiveFirstOption"
[requireSelection]="reactiveRequireSelection">
[requireSelection]="reactiveRequireSelection"
[revertToValue]="reactiveRevertToValue">
@for (state of reactiveStates; track state; let index = $index) {
<mat-option [value]="state" [disabled]="reactiveIsStateDisabled(state.index)">
<span>{{ state.name }}</span>
Expand Down Expand Up @@ -59,6 +60,20 @@
Require Selection
</mat-checkbox>
</p>
<p>
<mat-form-field>
<mat-label>Revert value to</mat-label>
<mat-select [(ngModel)]="reactiveRevertToValue" [disabled]="!reactiveRequireSelection">
<mat-option [value]="null">None</mat-option>
@for (state of states; track state) {
<mat-option [value]="state">
<span>{{ state.name }}</span>
<span class="demo-secondary-text"> ({{ state.code }}) </span>
</mat-option>
}
</mat-select>
</mat-form-field>
</p>

</mat-card>

Expand All @@ -76,7 +91,8 @@
<mat-autocomplete #tdAuto="matAutocomplete"
[hideSingleSelectionIndicator]="templateHideSingleSelectionIndicator"
[autoActiveFirstOption]="templateAutoActiveFirstOption"
[requireSelection]="templateRequireSelection">
[requireSelection]="templateRequireSelection"
[revertToValue]="templateRevertToValue">
@for (state of tdStates; track state) {
<mat-option [value]="state.name"
[disabled]="templateIsStateDisabled(state.index)">
Expand Down Expand Up @@ -113,6 +129,19 @@
Require Selection
</mat-checkbox>
</p>
<p>
<mat-form-field>
<mat-label>Revert value to</mat-label>
<mat-select [(ngModel)]="templateRevertToValue" [disabled]="!templateRequireSelection">
<mat-option [value]="null">None</mat-option>
@for (state of states; track state) {
<mat-option [value]="state.name">
<span>{{ state.name }}</span>
</mat-option>
}
</mat-select>
</mat-form-field>
</p>
<p>
<label for="template-disable-state-options">Disable States</label>
<select [(ngModel)]="templateDisableStateOption" id="template-disable-state-options">
Expand Down
5 changes: 5 additions & 0 deletions src/dev-app/autocomplete/autocomplete-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatButtonModule} from '@angular/material/button';
import {MatCardModule} from '@angular/material/card';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatSelectModule} from '@angular/material/select';
import {ThemePalette} from '@angular/material/core';
import {MatDialog, MatDialogRef} from '@angular/material/dialog';
import {MatInputModule} from '@angular/material/input';
Expand Down Expand Up @@ -42,6 +43,7 @@ type DisableStateOption = 'none' | 'first-middle-last' | 'all';
MatCardModule,
MatCheckboxModule,
MatInputModule,
MatSelectModule,
ReactiveFormsModule,
],
changeDetection: ChangeDetectionStrategy.OnPush,
Expand All @@ -68,6 +70,9 @@ export class AutocompleteDemo {
reactiveRequireSelection = false;
templateRequireSelection = false;

reactiveRevertToValue = null;
templateRevertToValue = null;

reactiveHideSingleSelectionIndicator = false;
templateHideSingleSelectionIndicator = false;

Expand Down
9 changes: 7 additions & 2 deletions src/material/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -757,8 +757,13 @@ export class MatAutocompleteTrigger
this._element.nativeElement.value !== this._valueOnAttach
) {
this._clearPreviousSelectedOption(null);
this._assignOptionValue(null);
this._onChange(null);
if (panel.revertToValue) {
this._assignOptionValue(panel.revertToValue);
this._onChange(panel.revertToValue);
} else {
this._assignOptionValue(null);
this._onChange(null);
}
}

this.closePanel();
Expand Down
13 changes: 13 additions & 0 deletions src/material/autocomplete/autocomplete.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,19 @@ injection token.

<!-- example(autocomplete-require-selection) -->

### Revert to a given value instead of `null`

Instead of setting the autocomplete value to `null`, the `revertToValue` input can be set to
provide a value to be set instead. This is useful in cases where the autocomplete should change
to a previously known value or default value if nothing is selected, instead of `null`.

Because the value may not present in the filtered options, this does _not_ trigger the
`selectionChange` event. However, for both reactive and template form controls, the value will
be updated appropriately. This does mean that it is possible to set the value to something that
is not present in the options list.

<!-- example(autocomplete-revert-to-value) -->

### Automatically highlighting the first option

If your use case requires for the first autocomplete option to be highlighted when the user opens
Expand Down
91 changes: 91 additions & 0 deletions src/material/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2859,6 +2859,95 @@ describe('MatAutocomplete', () => {
expect(input.value).toBe('');
expect(stateCtrl.value).toBe(null);
}));

it('should revert to the provided value if requireSelection is enabled and revertToValue is provided', waitForAsync(async () => {
const input = fixture.nativeElement.querySelector('input');
const {stateCtrl, trigger} = fixture.componentInstance;
fixture.componentInstance.requireSelection = true;
fixture.componentInstance.revertToValue = {code: 'DE', name: 'Delaware'};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await new Promise(r => setTimeout(r));

// Simulate opening the input and clicking the first option.
trigger.openPanel();
fixture.detectChanges();
await new Promise(r => setTimeout(r));
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
await new Promise(r => setTimeout(r));
fixture.detectChanges();

expect(trigger.panelOpen).toBe(false);
expect(input.value).toBe('Alabama');
expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'});

// Simulate pressing backspace while focus is still on the input.
dispatchFakeEvent(input, 'keydown');
input.value = 'Alabam';
fixture.detectChanges();
dispatchFakeEvent(input, 'input');
fixture.detectChanges();
await new Promise(r => setTimeout(r));

expect(trigger.panelOpen).toBe(true);
expect(input.value).toBe('Alabam');
expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'});

// Simulate clicking away.
input.blur();
dispatchFakeEvent(document, 'click');
fixture.detectChanges();
await new Promise(r => setTimeout(r));

expect(trigger.panelOpen).toBe(false);
expect(input.value).toBe('Delaware');
expect(stateCtrl.value).toEqual({code: 'DE', name: 'Delaware'});
}));

it('should keep the input value if requireSelection is disabled and revertToValue is provided', waitForAsync(async () => {
const input = fixture.nativeElement.querySelector('input');
const {stateCtrl, trigger} = fixture.componentInstance;
fixture.componentInstance.requireSelection = false;
fixture.componentInstance.revertToValue = {code: 'DE', name: 'Delaware'};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
await new Promise(r => setTimeout(r));

// Simulate opening the input and clicking the first option.
trigger.openPanel();
fixture.detectChanges();
await new Promise(r => setTimeout(r));
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
await new Promise(r => setTimeout(r));
fixture.detectChanges();

expect(trigger.panelOpen).toBe(false);
expect(input.value).toBe('Alabama');
expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'});

// Simulate pressing backspace while focus is still on the input.
dispatchFakeEvent(input, 'keydown');
input.value = 'Alabam';
fixture.detectChanges();
dispatchFakeEvent(input, 'input');
fixture.detectChanges();
await new Promise(r => setTimeout(r));

expect(trigger.panelOpen).toBe(true);
expect(input.value).toBe('Alabam');
expect(stateCtrl.value).toEqual('Alabam');

// Simulate clicking away.
input.blur();
dispatchFakeEvent(document, 'click');
fixture.detectChanges();

await new Promise(r => setTimeout(r));

expect(trigger.panelOpen).toBe(false);
expect(input.value).toBe('Alabam');
expect(stateCtrl.value).toEqual('Alabam');
}));
});

describe('panel closing', () => {
Expand Down Expand Up @@ -3997,6 +4086,7 @@ const SIMPLE_AUTOCOMPLETE_TEMPLATE = `
[displayWith]="displayFn"
[disableRipple]="disableRipple"
[requireSelection]="requireSelection"
[revertToValue]="revertToValue"
[aria-label]="ariaLabel"
[aria-labelledby]="ariaLabelledby"
(opened)="openedSpy()"
Expand Down Expand Up @@ -4033,6 +4123,7 @@ class SimpleAutocomplete implements OnDestroy {
autocompleteDisabled = false;
hasLabel = true;
requireSelection = false;
revertToValue: {code: string; name: string; height?: number; disabled?: boolean} | null = null;
ariaLabel: string;
ariaLabelledby: string;
panelClass = 'class-one class-two';
Expand Down
12 changes: 12 additions & 0 deletions src/material/autocomplete/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ export interface MatAutocompleteDefaultOptions {
*/
requireSelection?: boolean;

/**
* If requireSelection is true, this input can be used to specify the value to revert to when
* the user closes the autocomplete panel without selecting an option. Defaults to null.
*/
revertToValue?: unknown | null;

/** Class to be applied to the autocomplete's backdrop. */
backdropClass?: string;

Expand Down Expand Up @@ -192,6 +198,12 @@ export class MatAutocomplete implements AfterContentInit, OnDestroy {
*/
@Input({transform: booleanAttribute}) requireSelection: boolean;

/**
* If requireSelection is true, this input can be used to specify the value to revert to when
* the user closes the autocomplete panel without selecting an option. Defaults to null.
*/
@Input() revertToValue: unknown | null = null;

/**
* Specify the width of the autocomplete panel. Can be any CSS sizing value, otherwise it will
* match the width of its host.
Expand Down