角度自动完成对象

时间:2018-05-21 11:24:05

标签: angular autocomplete

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

这是我的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()));
  }

1 个答案:

答案 0 :(得分:2)

你几乎就在那里,你只需要将数组映射到对象的内部属性。这是必要的,因为过滤函数的返回值是一个字符串数组。

let package = Package(
    name: "TestFramework",
    products: [
        // Products define the executables and libraries produced by a package, and make them visible to other packages.
        .library(
            name: "TestFramework",
            targets: ["TestFramework"]),
    ],

Demo

相关问题