Bailey Stein
Bailey Stein

Reputation: 331

Input value two-way data binding not updating with empty string

I'm using Angular 8.1.3. Here's my HTML...

<mat-form-field floatLabel="never">
  <input matInput placeholder="Address Line 2" [value]="addressLine2" [disabled]="disableAddressFields">
</mat-form-field>

I have the following in my TypeScript file.

addressLine2 = '';

Changing to a non-empty string is reflected in the HTML.

this.addressLine2 = 'some value';

But setting it back to an empty string does is not reflected in the HTML, despite the value being empty ('') in the TypeScript (confirmed by printing to console).

this.addressLine2 = '';

It seems that once a non-empty string is set in the TypeScript, an empty string that is set is not reflected in the HTML. I'm kind of lost here; any help would be greatly appreciated.

Upvotes: 0

Views: 2108

Answers (2)

alt255
alt255

Reputation: 3576

For two way binding to work you need to use [(ngModel)]. Import angular forms add add [(ngModel)] to your code.

 <input matInput placeholder="Address Line 2" [(ngModel)]="addressLine2" [disabled]="disableAddressFields">

In your current code you are binding input's value property to addressLine2 so it is working as expected. To also get data back from input field you need to use ngModel

  <input matInput placeholder="Address Line 2" [value]="addressLine2" [disabled]="disableAddressFields">

Upvotes: 2

Barkha
Barkha

Reputation: 722

Instead of [value]="addressline2", it should be [(ngmodel)]="addressline2" for two way binding

Upvotes: 0

Related Questions