用作 formControl 时,Mat Autocomplete 未设置输入值

Eri*_*rik 7 typescript angular-material angular

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 - /sf/answers/3925174221/

yur*_*zui 8

初始值不会反映在输入中,因为您使用 displayFn 转换器,该转换器将 value 作为尝试查找的对象obj.name字符串上的属性。

由于您将值设置为mat-autocompelte不需要product.name使用displayFn不需要

好的,您可以填充输入文本了。现在,您需要完成 ControlValueAccessor 实现。

有专门的onChange如果要将值传播到主机控制值,

onChange这意味着当您想要更新主机控件值时需要调用方法。如果是 mat-autocomplete,你可以听optionSelected

<mat-autocomplete ... (optionSelected)="onChange($event.option.value)">
Run Code Online (Sandbox Code Playgroud)

叉式堆栈闪电战