I have an input text box which use ngModel bind to a variable inside the component class. Upon clicking a button I want to clear the input text, however changing the variable value doesn't change the input text.
I have re-assign the variable and call detectChanges() from ChangeDetectorRef, but it still doesn't work.
This is the template that I have
<form #beaconForm="ngForm" autocomplete="off">
<input #searchBox
id="search-query"
name="search-query"
[ngModel]="inputValue"
(ngModelChange)="searchAutocomplete($event)"
(keydown)="onKeyDown($event, searchBox)"
(blur)="onBlur()"
(focus)="onFocused(searchBox.value)">
<button color="accent" mat-mini-fab (click)="action(searchBox.value)"><mat-icon>add</mat-icon></button>
</form>
Then on clicking action I want to do
private inputValue: string = "";
action(value) {
this.inputValue = "";
this.cd.detectChanges();
}
I'm expecting this to clear the input, but it doesn't. Any idea where's my mistake?
It should be [(ngModel)]="inputValue"
if you want two-way data binding. [ngModel]
works fine for one-way data binding.
Try changing the code as:
<form #beaconForm="ngForm" autocomplete="off">
<input #searchBox id="search-query" name="search-query"
\/\/
[(ngModel)]="inputValue"
(ngModelChange)="searchAutocomplete($event)"
(keydown)="onKeyDown($event, searchBox)"
(blur)="onBlur()"
(focus)="onFocused(searchBox.value)" >
<button color="accent" mat-mini-fab (click)="action(searchBox.value)">
<mat-icon>add</mat-icon>
</button>
</form>