角材料自动完成默认过滤器不起作用

时间:2020-04-20 13:20:03

标签: angular autocomplete angular-material

我正在使用Angular Material的Autocomplete组件,该组件工作正常,但搜索过滤器(该示例中的默认过滤器)除外,该过滤器不会根据我的输入进行搜索,仅显示所有元素当我开始打字时。

HTML:

<form (ngSubmit)="submit()" [formGroup]="pacientForm">
    <label class="example-radio-group">Disease</label>
              <input type="text"
               matInput
               [(ngModel)]="pacient.disease"
               formControlName="disease"
               [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let option of filteredDiseaseOptions | async" [value]="option">
            {{option}}
          </mat-option>
        </mat-autocomplete>

TS:

pacientForm: FormGroup = new PacientCreateFormBuilder().build();
pacient: Pacient;
diseaseOptions: string[] = ['first', 'second', 'third'];
filteredDiseaseOptions: Observable<string[]>;

ngOnInit(): void {
    this.filteredDiseaseOptions = this.pacientForm.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }

private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.diseaseOptions.filter(option => option.toLowerCase().includes(filterValue));
  }

FormGroup:

export class PacientCreateFormBuilder {

  public build(): FormGroup {
    return new FormGroup({
      disease: new FormControl('', []),
    });
  }

}

1 个答案:

答案 0 :(得分:0)

我认为您需要this.filteredDiseaseOptions = this.pacientForm.get('disease').valueChanges()

disease是您要订阅的表单控件名称。