【问题标题】:Angular Autocomplete Object角度自动完成对象
【发布时间】:2018-10-31 01:11:20
【问题描述】:

我正在努力了解如何在使用对象时使用 Angular Material Autocomplete。我基本上遵循了 Angular Docs,只是用选项对象替换了选项数组,但我不确定如何让它工作。介意看看这里吗?如果其他地方有很多答案,我将删除该问题。

这是我的 html 和 ts 组件。所有的导入和一切都绝对正确,所以我没有显示任何内容。

<mat-form-field>
  <input matInput [formControl]="myControl" [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
      {{ option }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

  ###############################

  myControl: FormControl = new FormControl();
  filteredOptions: Observable<string[]>;

  options = [
    {color: 'One'},
    {color: 'Two'},
    {color: 'Three'},
  ];

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(val => this.filter(val))
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().includes(val.toLowerCase()));
  }

【问题讨论】:

    标签: angular autocomplete


    【解决方案1】:

    您就快到了,您只需要将数组映射到对象的内部属性。这是必要的,因为您的过滤器函数的返回值是一个字符串数组。

    filter(val: string): string[] {
      return this.options.map(x => x.color).filter(option =>
        option.toLowerCase().includes(val.toLowerCase()));
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 2021-02-05
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2016-11-22
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多