首页 > 解决方案 > 材料角度自动完成:选择选项后如何在屏幕中保留垫子选项?

问题描述

我正在使用Material 自动完成 angular。在我的mat-option列表中选择一个选项后,我的mat-options隐藏。选择后我需要保留选项。显示问题的 GIF:

在此处输入图像描述

我的html

<div class="col-xl-6 margemColunas">
    <label>Anunciaremos nas contas *</label>
     <input class="form-control inputContasB2W"
          #inputContasB2W
          [formControl]="contasB2WControl"
          [matAutocomplete]="auto"
          (matChipInputTokenEnd)="add($event)">
      <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event, i)">
        <mat-option *ngFor="let contaB2W of contasFiltradas | async" [value]="contaB2W">
          {{contaB2W}}
        </mat-option>
      </mat-autocomplete>
</div>

<div class="col-xl-6 alinhaChips">
  <mat-chip-list>
    <mat-chip
    *ngFor="let contaB2W of produto.contasAnunciarB2W; let j = index"
    [selectable]="selected"
    [removable]="removable"
    (removed)="removeTag(i, j)">
    {{contaB2W}}
    <mat-icon matChipRemove><i class="fa fa-close"></i></mat-icon>
  </mat-chip>
  </mat-chip-list>
</div>

我的ts:

constructor(){
    this.contasFiltradas = this.contasB2WControl.valueChanges.pipe(
      startWith(null),
      map((nomeConta: string | null) => nomeConta ? this._filter(nomeConta) : this.contasB2W.slice()));
}

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();
    return this.contasB2W.filter(conta => conta.toLowerCase().indexOf(filterValue) === 0);
  }

selected(event: MatAutocompleteSelectedEvent, index: number): void {

 this.produtosConfirmadosAnuncio[index].contasAnunciarB2W.push(event.option.viewValue);

    this.inputContasB2W.nativeElement.value = '';

          } 
        }

标签: htmlangulartypescriptangular-material

解决方案


我使用了解决方法blur(),然后focus()再次输入。

在 ts 中:

@ViewChild('inputContasB2W') autocompleteInput: ElementRef;

selected(event: MatAutocompleteSelectedEvent) {
  [..do your stuff...]

  this.autocompleteInput.nativeElement.blur();
  setTimeout(() => {
      this.autocompleteInput.nativeElement.focus();
    }, 100
  );
}

如果要保留输入文本,则必须将其保存并在之前_filter()再次设置值blur()this.contasB2WControl.setValue(this.lastFilterValue);


推荐阅读