How to pre-select an option in mat-autocomplete

See original GitHub issue

Question:

How to pre-select an option in mat-autocomplete

What is the expected behavior?

Value to be prefilled in the autocomplete when loading a component for editing.

What is the current behavior?

I am not able to prefill the value which i get from the server.

What are the steps to reproduce?

Below is the Code i am using

component.ts this.filteredData = this.addDetailsForm.get('product').valueChanges
.debounceTime(400) .do(value => { let exist = this.myContent.findIndex(t => t.text === value); if (exist > -1) return; this._dataService.getSwiftProducts(value).subscribe((res: any[]) => { this.myContent = res; }); }).delay(500).map(() => this.myContent);

component.html <div class="row"> <label class="col-lg-4 control-label">Product: </label> <div class="col-lg-5"> <input type="text" class="form-control" (keyup.enter)="chooseFirstOption()" placeholder="Pick one" aria-label="Number" matInput ="product" formControlName="product" [matAutocomplete]="auto"> <p *ngIf="addDetailsForm.controls.product.errors">This field is required!</p> <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn"> <mat-option *ngFor="let option of filteredData | async" [value]="option"> {{ option.description }} </mat-option> </mat-autocomplete> </div> </div>`

What is the use-case or motivation for changing an existing behavior?

To edit a record

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular : “@angular/core”: “^5.0.0”, Material : “@angular/material”: “^5.0.0-rc0”, OS: Windows 7 Typescript : “typescript”: “^2.6.2”

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

11reactions
julianobrasilcommented, Oct 27, 2018

Default value?.. well, if you have a default value, the autocomplete will bring you just one option if you set an object to the input value (the default value selected) or a list of possible objects if it is a string. I’m not sure I’m following you… I suppose you have something like this in your code:

<input [formControl]="_inputCtrl" [matAutocomplete]="auto">
<mat-autocomplete #auto>
  <mat-option *ngFor="let option of _options$ | async"
              [value]="option"
              [displayWith]="_displayWithLabel()">
      {{option.label}}
  </mat-option>
</mat-autocomplete>
class MyClass {
  label: string;
  value: any;
}

....

_displayWithLabel = () => (value: MyClass | string): string => {
   return !value 
    ? '' 
    : typeof value === 'string' 
      ? value
      : value.label;
}

....

_options$: Observable<MyClass[]>;
constructor(private _service: MyHttpService) {
  this._options$ = _inputCtrl.valueChanges.pipe(
    startWith(null),
    debounce(300),
    switchMap((value: MyClass | string) => this._getOptions(value))
    takeUntil(this._componentDestroyed$),
  );

  // here you set the default selected value: it should fire the valueChanges event set above and
  // get you a list of options, if there was any based on your default initial value.
  this._inputCtrl.setValue('someDefaultStringToStartWith');
}

private _getOptions(value: MyClass | string): Observable<MyClass[]> {
  if(typeof value === 'string') {
    return this._service.getObjectsByLabel(value);
  } else {
    return of([value])
  }
}
5reactions
julianobrasilcommented, Oct 29, 2018

But if you consider the edit page there should be prefilled value. Which the user can remove and then use autocomplete. If the user doesn’t wants to change the value why empty such an input field.

The example above should do it. There’s no need to recreate the input control everytime.

this._inputCtrl.setValue(...) is enough.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to pre-select an option in mat-autocomplete
Need to assign a FormControl object on the html input element as shown below. Then in the TS file you can call setValue...
Read more >
Autocomplete | Angular Material
The autocomplete is a normal text input enhanced by a panel of suggested options. link Simple autocomplete. Start by creating the autocomplete panel...
Read more >
How To Set Default Value Of Mat Select When Options Are ...
Editor Preview Both. Sign in. Project. Search. Settings. Switch to Light Theme. Enter Zen Mode. Project. Download Project. Info. How To Set Default...
Read more >
mat-select, mat-autocomplete tooltip, mat-autocomplete opened,
Question: How to pre-select an option in mat-autocomplete What is the expected behavior? Value to be prefilled in the autocomplete when loading a...
Read more >
Angular material multi-select with autocomplete - Medium
selectedOptions (Array of Strings): To pre-populate or preselect options. display (String): Property of every option for display in dropdown.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found