4

Edit: Resolved with Jojofoulk's comment.

when using the autocomplete components of angular-material, I'm trying to use setValue to the input form, but its [matAutocomplete] attribute is preventing setValue from showing on the input.

Inspecting the reactive control reveals the value is right, and removing [matAutocomplete] makes it work, but with it it's just not showing up.

<mat-list-item role="listitem" *ngFor="let skill of curObj.skills;index as ind">
  <div>
    <mat-form-field>
      <input type="text" placeholder="choose skill" aria-label="Number" matInput [formControl]="skill.control" [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="optSel($event.option.value,skill)">
        <mat-option *ngFor="let option of skill.filteredOptions | async" [value]="option">
          {{option.name}}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>
  </div>
</mat-list-item>
skill.control.setValue("some new value");
Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
user1037607
  • 133
  • 2
  • 12
  • Why do you want some different value for the input and still want mat-autocomplete to be attached with that input. – Pankaj Prakash Jun 05 '19 at 04:49
  • Because I'm also changing it by code following outside actions. – user1037607 Jun 05 '19 at 04:53
  • It would be great if you provide the stackblitz for the same. – Yash Rami Jun 05 '19 at 05:03
  • 1
    Assuming your `displayFn` is to display a certain property from an Object, are you making sure you are using `setValue()` to set the whole object object and not just the display value? The input should have the whole object when you couple it with the autoComplete using `[displayWith]` Little example: https://stackblitz.com/edit/angular-sjktt2 – Jojofoulk Jun 05 '19 at 05:04
  • It worked! Thanks man, good job! – user1037607 Jun 05 '19 at 05:15

1 Answers1

8

The displayFn takes the input to display it differently (usually a property of an object in your input), but it takes the whole object! You should make sure you are using setValue() to set an object and not just the value you want to display.

The input should hold the whole object when you couple it with the [matAutoComplete] using [displayWith], the displayFn will take care of filling your input.

Little example

Jojofoulk
  • 2,127
  • 1
  • 7
  • 25