Angular input text field does not dynamically clear with empty string

Viewed 500

I am trying not to use the following (in my app.component.html)

<input type="text" class="form-control" [(ngModel)]="username">

<button class="btn btn-primary" [disabled]="username === ''" (click)="onResetUser()">
    Reset User
</button>

with the logic in app.component.ts

export class AppComponent {

  username: string = "";

  onResetUser() {
    this.username = "";
  }
}

but instead get the following to work dynamically:

<input type="text" class="form-control" (input)="onUpdateUsername($event)">

<button class="btn btn-primary" [disabled]="usernameFieldEmpty" (click)="onResetUser()">
    Reset User
</button>

and the logic:

export class AppComponent {

  username: string = "";
  usernameFieldEmpty: boolean = true;

  onResetUser() {
    this.username = "";
    this.usernameFieldEmpty = true;
  }

  onUpdateUsername(event: any) {
    this.username = event.target.value;
    this.setUsernameFieldStatus();
  }

  setUsernameFieldStatus() {
    this.username === "" ? 
      this.usernameFieldEmpty = true : 
      this.usernameFieldEmpty = false;
  }
}

The disabling part works correctly, but in the second case, when I click the reset button, the content of the input field does not clear. What am I missing?

2 Answers

You are never passing the value back to your input. The following should do the trick.

<input type="text" class="form-control" [ngModel]="username" (input)="onUpdateUsername($event)">

There is a way to fix this for all your components TLDR: add this to your AppModule:

    DefaultValueAccessor.prototype.registerOnChange = function (fn: (_: string | null) => void): void {
      this.onChange = (value: string | null) => {
        fn(value === '' ? null : value);
      };
    };

To summarize, this is a known issue is angular that reported here: https://github.com/angular/angular/issues/45317 And can't be fixed unless you use this little hack because of much older issue explained here: https://github.com/angular/angular/issues/3009 That prevent overriding the default behavior of angular globally. Hope it helps.

Related