How to pre-select an option in mat-autocomplete
See original GitHub issueQuestion:
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:
- Created 6 years ago
- Comments:12 (5 by maintainers)
Top Related StackOverflow Question
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:
The example above should do it. There’s no need to recreate the input control everytime.
this._inputCtrl.setValue(...)is enough.