Changing value bind to ng-model doesn't change the value on the input text

user3794740 picture user3794740 · Apr 9, 2019 · Viewed 7.1k times · Source

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?

Answer

Prashant Pimpale picture Prashant Pimpale · Apr 9, 2019

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>

Stackblitz