MatAutocomplete with observables

时间:2017-10-28 13:25:02

标签: angular angular-material observable

我正在使用素材自动填充组件。

我输入的第一个字母输入,它按预期工作,但接下来失败。

这显然是因为我为this.filteredUnitName设置了新值:

export class ActionDetailComponent {
    @Input() unitNames: Observable<string[]>;

    filteredUnitNames: Observable<string[]>;

    unitName: FormControl = new FormControl();

    ngOnInit() {
        this.filteredUnitNames = this.unitName.valueChanges
            .startWith(null)
            .do(val => {
                if (val) {
                    this.filteredUnitNames = this.filter(val); // bad line
                }
            });
    }

    filter(val: string): Observable<string[]> {
        return this.unitNames
            .map(response => response.filter(
                option => option.toLowerCase().indexOf(val.toLowerCase()) === 0
            ));
    }

这是我的模板:

<mat-form-field>
    <input matInput placeholder="Unit name" class="form-control" [formControl]="unitName" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let name of filteredUnitNames | async" [value]="name">
        <span>{{name}}</span>
    </mat-option>
    </mat-autocomplete>
</mat-form-field>

还有其他方法可以使其正常工作吗?

1 个答案:

答案 0 :(得分:3)

您可以使用 switchMap 运算符实现此目的,因此请将代码更改为以下内容:

import "rxjs/add/operator/switchMap";


ngOnInit() {
  this.filteredUnitNames = this.unitName.valueChanges
    .startWith(null)
    .switchMap(val => {
      return this.filter(val || '')
   })
}

filter(val: string): string[] {
  return this.unitNames
    .map(response => response.filter(option => { 
       return option.toLowerCase().indexOf(val.toLowerCase()) === 0
    }));
}

DEMO:https://plnkr.co/edit/yb4NeYTbGkwHay15R8CW?p=preview

相关问题