Clear Angular Material autocomplete on click

本小妞迷上赌 提交于 2021-01-07 02:40:00

问题


Hi I want reset value of angular material autocomplete on click But I don't know how do.

My code :

  <mat-form-field>
        <input type="text" placeholder="Give Rights" formControlName="selectedOption" aria-label="User" matInput  [matAutocomplete]="auto" (input)="onSearchChange($event.target.value)">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let user of users" [value]="user.displayName" (onSelectionChange)="setSelectedUser($event, user)">
                {{ user.displayName }}
            </mat-option>
        </mat-autocomplete>
        <button (click)="resetValue($event)">RESET</button>
    </mat-form-field>

TS :

    this.nameForm = this._formBuilder.group({
    selectedOption: new FormControl()
});    

    resetValue(){
    console.log("Value -> ", this.nameForm.value.selectedOption);
    this.nameForm.value.selectedOption = "test";
}

Can you help me ?


回答1:


You can use two-way data binding to bind the input value to a property of the class, and use resetValue to act on that property.


<input [(ngModel)]="selectedOption" ...

resetValue() {
  this.selectedOption = '';
}

See working example here




回答2:


First you need to get a handle to the control whose value you want to set, you can do this using FormGroup's get method

nameForm.get('selectedOption')

Then you can simply call the setValue method provided by Reactive Forms to set the value of that control.

<button (click)="nameForm.get('selectedOption').setValue('')">RESET</button>



回答3:


What worked for me was adding a local reference to the input control and using that to set the value to empty when an option is clicked:

input
    #matInput
    type="text"
    placeholder="Search"
    aria-label="Search"
    matInput
    [formControl]="search"
    [matAutocomplete]="auto">
  <mat-autocomplete
    #auto="matAutocomplete"
    (optionSelected)="onOptionSelected($event)"
    panelWidth="auto">
    <mat-option *ngFor="let item of items | async"
      [value]="item.Key"
      (click)="matInput.value=''">
      {{ item.Name }}
    </mat-option>
  </mat-autocomplete>



回答4:


Your syntax doesn't look right. Try this.nameForm.controls['selectedOption'].setValue('test');



来源:https://stackoverflow.com/questions/50904900/clear-angular-material-autocomplete-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!