根据具体情况显示属性,并具有形式自动完成功能

问题描述 投票:0回答:1

我在 Angular v18 项目中使用 Formly Autocomplete,我不确定如何添加一个 displayWith 属性,该属性将使用一些函数与我的 Formly Autocomplete 字段相结合,以唯一地显示我在 Formly 中显示的对象中存在的属性领域。

autocomplete-type.component.ts

@Component({
  selector: 'formly-autocomplete-type',
  template: `
    <input
      matInput
      [matAutocomplete]="auto"
      [formControl]="formControl"
      [formlyAttributes]="field"
      [errorStateMatcher]="errorStateMatcher"
    />
    <mat-autocomplete
      #auto="matAutocomplete"
      [autoActiveFirstOption]="true"
      [autoSelectActiveOption]="true"
    >
      <mat-option *ngFor="let value of filter | async" [value]="value">
        {{ value }}
      </mat-option>
    </mat-autocomplete>
  `,
})
export class AutocompleteTypeComponent
  extends FieldType<FieldTypeConfig>
  implements OnInit {}

example of a field

{
      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()
          ),
      },
    },

我知道我可以在项目中编辑自动完成组件,但我不太确定如何采取最后一步为 displayWith 提供灵活的值。

angular angular-formly
1个回答
0
投票

不要使用 Material Autocomplete 的 displayWith 属性,而是从 Formly 字段的 props 访问 displayProp 属性。

template: `
    <input
      matInput
      [matAutocomplete]="auto"
      [formControl]="formControl"
      [formlyAttributes]="field"
      [errorStateMatcher]="errorStateMatcher"
    />
    <mat-autocomplete
      #auto="matAutocomplete"
      [autoActiveFirstOption]="true"
      [autoSelectActiveOption]="true"
    >
      <mat-option *ngFor="let value of filter | async" [value]="value">
        {{ value[props['displayProp']] }}
      </mat-option>
    </mat-autocomplete>
  `,

{
      key: 'workCenterCode',
      type: 'autocomplete',
      props: {
        required: true,
        label: 'Work Center Code',
        placeholder: 'Work Center Code',
        displayProp: 'NAME',
        filter: (term: string) =>
          of(
            term
              ? this.workOrderInputsService.filterObjectArray(
                  term,
                  this.workCenterCodeArray,
                  'NAME'
                )
              : this.workCenterCodeArray.slice()
          ),
      },
    },

© www.soinside.com 2019 - 2024. All rights reserved.