7

I would like to get a value from a database and set it as a default value in an autocomplete input box.

populate clientTypes

clientTypes: any[] = [];
getClientTypes() {
    this.clientService.getClientTypes()
    .subscribe((data: any) => {
        this.clientTypes = [...data];
    });
}

for Autocomplete DisplayWith

displayFn(object): string {
    console.log(object.ClientTypeId);
    return object.Name;
}

in the html

<mat-form-field appearance="outline">
    <mat-label>Client Type</mat-label>
    <input type="text" placeholder="Select Client Type" aria-label="Number" matInput formControlName="clienttype"  [formControl]="clientTypeControl" [matAutocomplete]="auto3">
    <mat-autocomplete #auto3="matAutocomplete" [displayWith]="displayFn" (optionSelected)='setClientTypeId($event.option.value)'>
        <mat-option *ngFor="let clientType of clientTypes" [value]="clientType">
            {{ clientType.Name }}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>
<br>

When I use the edit, I get the saved accountTypeId from the database. My problem lies on how to place the fetched accounTypeId into the the matautocomplete as a default option selected but still get the rest of the options?

Thank you.

Aamir Khan
  • 2,945
  • 2
  • 25
  • 32
stack questions
  • 862
  • 2
  • 15
  • 29
  • also see this for an example - https://stackoverflow.com/questions/56208062/how-to-set-default-values-for-mat-autocomplete – JimiSweden Jun 29 '21 at 11:42

1 Answers1

0

You can achieve this in one of two ways:

  1. Create a property in the ts file and assign a default value to this on ngOnInit and use model binding [(ngModel)]="your property" in the input control to set the default value.
  2. Use patchValues and assign a value to your form control on ngOnInit.
jtate
  • 2,612
  • 7
  • 25
  • 35
JanakaRao
  • 71
  • 7