【问题标题】:Autocomplete Material show [object object]自动完成材质显示 [object object]
【发布时间】:2020-01-25 13:26:36
【问题描述】:

自动完成材质实现,但从列表中选择一个项目显示为 [object object]。

为了显示需要使用此模块的数据数组,我将其应用于以下视图。

<mat-form-field>
  <input type="text" matInput [matAutocomplete]="auto" formControlName="item">
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="itemDataChange($event)" 
      [displayFn]="displayFn">
    <mat-option *ngFor="let item of itemsListFiltrado | async" [value]="option.value"> 
      {{option.option}}</mat-option>
  </mat-autocomplete>
</mat-form-field>

我需要使用所选项目的 value 属性,但我想显示它的选项。这些属性符合控制器中应用的接口。

我使用此过程对数组 itemsList 应用过滤:

export interface Option {
  option: string;
  value: string;
}

// (...)


public itemsList: Option[] = [];
public itemsListFiltrado: Observable<Option[]>;
public codigoArticuloInsrt: number;

filterItems(option: any) {
  const filterValue = option.toString().toLowerCase();
      const filterList = this.itemsList.filter(indexArt => 
        indexArt.option.toLowerCase().indexOf(filterValue) === 0);
      if (filterList.length === 1) {
        // property used for data saving
        // for saving the form for saving the form
        this.codigoItemInsrt = parseInt(filterList[0].value, 0);
      }
      return filterList;
   }
listFltr() {
  return this.itemsListFiltrado =

    // when the controller changes value 
    this.editDetailLineForm.controls.item.valueChanges
      .pipe(
        startWith(''),
        map(param => this.filterItems(param))
      );
  }

最后在调用将数据加载到数组的服务的方法中实例化。

Github 中找到的旧线程中,我使用了 displayWith 属性,但没有得到任何更改。

displayFn(i: Option) {
    if (i) { return i.option; }
  }

【问题讨论】:

    标签: angular autocomplete angular-material


    【解决方案1】:

    你的方法被调用了吗?尝试写入函数内部的控制台以进行验证。您可能需要将displayFn 设为箭头函数,如:

    displayFn = (i: Option) => {
      console.log('in displayFn, param = ', i);
      if (i) {
        console.log('returning i.option', i.option);
        return i.option;
      } else {
        console.log('no Option');
        return undefined;
      }
    }
    

    如果在所有这些之后,您的方法 正在 被调用,并且没有其他任何事情是显而易见的, i.option 是字符串还是对象?

    【讨论】:

    • i.option 是一个字符串。对象由选项和值组成。
    猜你喜欢
    • 2021-01-14
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多