Erik
Erik

Reputation: 957

Mat Autocomplete not setting input value when used as a formControl

I have a custom autocomplete component that implements ControlValueAccessor. From the parent component I am trying to set the value using form.get('productName').setValue('Product 1');. This sets the value in the form but it's not reflected in the input that is associated to the autocomplete.

I have a stackblitz example that shows the input not displaying the value. As soon as I remove the attribute [matAutocomplete]="auto" from the input, the value is visible in the UI.

https://stackblitz.com/edit/angular-autocomplete-form-control?file=src%2Fapp%2Fapp.component.ts

I have tried what they mentioned here but no success either - https://stackoverflow.com/a/56073917/4142653

Upvotes: 7

Views: 10643

Answers (1)

yurzui
yurzui

Reputation: 214175

Initial value is not reflected in the input because you use displayFn transformer that works with value as an object where tries to find obj.name property on string.

Since you're setting value to mat-autocompelte as product.name you don't need to use displayFn at all.

Ok, you're able to populate input text. Now, you need to finish your ControlValueAccessor implementation.

There is dedicated onChange method that should be called if you want to propagate value to the host control value.

It means you need to call onChange method when you want to update host control value. In case of mat-autocomplete you can listen to optionSelected:

<mat-autocomplete ... (optionSelected)="onChange($event.option.value)">

Forked Stackblitz

Upvotes: 8

Related Questions