简体   繁体   中英

prefill mat-autocomplete in angular 2 material 2

I am not able to set the value of the mat-autocomplete when I am trying to edit a record I am using the autocomplete as a FormControl object in a FormBuilder object and to set values received from the server I am using Formbuilder.setValue() method, but this does not set autocomplete although it sends a request to the server as I am using the valueChanges method of Observables... any help would be appreciated.

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>

Versions of Angular, Material, OS, TypeScript:

Angular : "@angular/core": "^5.0.0",

Material : "@angular/material": "^5.0.0-rc0",

OS: Windows 7

Typescript : "typescript": "^2.6.2"

After a lot of research and even irritating the development team of Angular Material i realized that the response i was sending while trying to edit a record was incorrect. I was sending a string as a response for the autocomplete whereas it was supposed to be an Object. It depends really on how the displayFn function is written. Below is my displayFn function

displayFn(object): string {
console.log("Display Object is ---> " + object);
return object ? object.description : object;

}

So i needed to send an Object as a response.. My apologies to people i might have bugged..

You can simply do this once your form loads. You shouldn't need all those timeouts.

this.formControls.get('controlName').setValue(option.value);
  1. Replace "formControls" with the name of formBuilder group (not sure what the name of this is in your code as you didn't provide that)
  2. Replace "controlName" with the name of the input control (in your case it's 'product')
  3. Replace 'option.value' with whatever you want to prepopulate the autocomplete with. This will need to be a string value.

caution

if your autocomplete pools values from an array that comes from server or any async function, make sure you only try to set the default value after that array is initialized. for instance, if you are fetching a list of product names from server, wait until the product list is initialized. setting default value before that will not persist. it might even throw change detection error.

solution

use formControl.patchValue() or if that does not work, use viewChild to select the input element and explicitly set the value property.

@ViewChild('inputTempRef', {static: false}) myInput: ElementRef;

and finally when your array is initialized, do this:

myInput.nativeElement.value = 'presetValue'

I had the same problem and this code helped me:

displayWithSector(sector: Setor): string {
  return typeof sector !== 'string' ? sector.description : sector;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM