Angular v18中Formly Autocomplete的displayWith属性配置问题
给Formly Autocomplete添加自定义displayWith属性
要实现灵活的对象属性显示,你需要分两步修改:先扩展Autocomplete组件支持displayWith配置,再在字段定义中传入自定义显示逻辑。
1. 修改AutocompleteTypeComponent组件
更新组件类和模板,添加displayWith的支持:
@Component({ selector: 'formly-autocomplete-type', template: ` <input matInput [matAutocomplete]="auto" [formControl]="formControl" [formlyAttributes]="field" [errorStateMatcher]="errorStateMatcher" /> <mat-autocomplete #auto="matAutocomplete" [autoActiveFirstOption]="true" [autoSelectActiveOption]="true" [displayWith]="displayFn" <!-- 新增displayWith绑定 --> > <mat-option *ngFor="let value of filter | async" [value]="value"> {{ displayFn(value) }} <!-- 用displayFn渲染选项文本 --> </mat-option> </mat-autocomplete> `, }) export class AutocompleteTypeComponent extends FieldType<FieldTypeConfig> implements OnInit { // 自定义显示函数,优先使用字段配置的displayWith displayFn = (value: any) => { if (!value) return ''; // 如果字段props里定义了displayWith,就用它处理值,否则直接返回值 return this.field.props.displayWith?.(value) || value; }; }
2. 在字段配置中添加displayWith逻辑
在你的字段定义里,通过props.displayWith传入自定义函数,指定如何显示对象的属性:
{ key: 'workCenterCode', type: 'autocomplete', props: { required: true, label: 'Work Center Code', placeholder: 'Work Center Code', filter: (term: string) => of( term ? this.workOrderInputsService.filterObjectArray( term, this.workCenterCodeArray, 'NAME' ) : this.workCenterCodeArray.slice() ), // 新增:自定义显示逻辑,这里显示对象的NAME属性 displayWith: (item: any) => item.NAME, }, },
这样设置后,选中的对象会通过你指定的displayWith函数转换成文本显示在输入框里,下拉选项也会用同样的逻辑渲染,保证显示一致性。
内容的提问来源于stack exchange,提问作者Kafrizz
相关产品推荐
相关产品推荐

