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

时间:2019-10-30 10:32:25

标签: autocomplete angular-material

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

以下是说明问题的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('');
  }

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

如果您使用Form控件名称(在FormGroup内部),则无需使用Form控件。

我建议使用FormControl并设置:

ngOnInit() {
  this.myControl = new FormControl({'', disabled: this.options.length < 1});
  this.filteredOptions = this.myControl.valueChanges.pipe(
    startWith(''),
    map(value => { return this._filter(value)})
  );
}

clear() {
  this.myControl.patchValue('');
}

应该工作