选择后重置自动完成输入,然后显示所有选项

问题描述 投票:0回答:1

我有一个自动完成输入,问题是每当我重置输入值时,它都不会重置选择选项。它仅显示最新选择。

以下是说明问题的GIF:https://recordit.co/aVXqlPYHFQ

我尝试用this.form.get('panelForm').setValue('');重置输入但不重置选项

这是我的代码

<form *ngIf="options.length">
  <mat-form-field [formGroup]="form">
    <input type="text" [placeholder]="'Panel'" aria-label="Panel" matInput [formControl]="myControl" [formControlName]="'panelForm'" [matAutocomplete]="auto">
    <button mat-button mat-icon-button matSuffix (click)="clear()" *ngIf="form.get('panelForm')">
      <mat-icon>close</mat-icon>
    </button>
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)='selectPanel($event.option.value)'>
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
        {{option.name}} ({{option.genesCount}})
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
  myControl = new FormControl();
  filteredOptions: Observable<Panel[]>;
  public form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges.pipe(
      startWith(''),
      map(value => { return this._filter(value)})
    );

    this.form = this.fb.group({
      panelForm: new FormControl({ value: '', disabled: this.options.length < 1})
  });
  }

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

    return this.options.filter(option => option.name && option.name.toLowerCase().includes(filterValue));
  }

  clear(){
    this.form.get('panelForm').setValue('');
  }
autocomplete angular-material
1个回答
0
投票

尝试直接在html中直接重置值:

<form *ngIf="options.length">
  <mat-form-field [formGroup]="form">
    <input #myInput type="text" [placeholder]="'Panel'" aria-label="Panel" matInput [formControl]="myControl" [formControlName]="'panelForm'" [matAutocomplete]="auto">  // <-- set name here 'myInput'
    <button mat-button mat-icon-button matSuffix (click)="clear()" *ngIf="form.get('panelForm')">
      <mat-icon>close</mat-icon>
    </button>
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (optionSelected)="selectPanel($event.option.value);myInput.value=''">  // <-- reset value here
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
        {{option.name}} ({{option.genesCount}})
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>
热门问题
推荐问题
最新问题