问题
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