过滤列表并自动设置过滤列表的最后一个值

时间:2019-03-28 11:34:11

标签: angular angular-reactive-forms

我有一个使用mat-autocomplete的html输入框,该输入框过滤掉了值更改列表,效果很好。实际上,我想将数组的最后剩余值自动设置为输入框,这也可以正常工作,但是问题是设置值后,我无法使用退格键在浏览器的输入框中清除该值。下面是为简化起见而缩短的代码。

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

和.ts文件中

filteredOptions: Observable<string[]>;
options: ['one', 'two', 'three', 'four', 'five', 'six'] // for demo purpose
filteredArr;

ngOnInit() {
  this.filteredOptions = this.myForm.get('charge').valueChanges
  .pipe(map(value => this._filter(value)));
}

private _filter(val) {
  const filterValue = val.toLowerCase();
  this.filteredArr = this.options.filter(option => option.toLowerCase().includes(filterValue));
  if(this.filteredArr.length == 1) {
    // tried with setValue too, same result
    this.myForm.get('charge').patchValue(this.filteredArr[0], {emitEvent: false});
    this.filteredArr = [];
    return this.filteredArr;
  }
  return this.filteredArr;
}

先谢谢了。让我知道是否需要更多信息。

0 个答案:

没有答案