• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

384
Views
Angular: Setting an emptied string to a default value does not update the bound text field properly if the field previously had the default value

I'm using a SET method to set my bound value to 'DEFAULT' if we ever attempt to set it to an empty string. The bound text input behaves properly in every scenario, EXCEPT if the text field already says 'DEFAULT' and I "select all + delete" that value. The bound value properly gets set back to 'DEFAULT' immediately, but the input field remains empty.

The get/set methods

the template

Here's a stackblitz showing the issue https://stackblitz.com/edit/angular-a9j8tv?file=src%2Fapp%2Fapp.component.html

If you have 'DEFAULT' and you select all and delete, you can see that the input stays empty, but the span which is bound to the same value properly shows the newly re-set 'DEFAULT' value.

Why does this happen? Is there a work around?

over 3 years ago · Santiago Trujillo
2 answers
Answer question

0

The issue comes from ngModel. That since the '' value manipulating to the DEFAULT, which is the latest value that has been fired by ngModel, ngModel does not realize the value change to fire new value changed event.

How to workaround;

I have assigned the changed value directly to the variable in the setter before comparison. Then set a minimal timeout to ngModel could update its existing value. Then when I compare the new value and change it back to DEFAULT in the case of '', ngModel realizes the value change and fires the new value changed event. This updates both representations.

Please find updated stackblitz

over 3 years ago · Santiago Trujillo Report

0

Inherent error

The ngModel directive uses @Input and @Output to obtain the value and emit the change event. So binding a function like setter or getter to a directive like [ngModel] with default change detection strategy would trigger the function for each change detection.

To replicate this error, plug in a console.log in the getter, type some value and keep pressing backspace in the <input> and let go. You could see the console.log messages keeps getting printed.

Error replication: Stackblitz


Why isn't 'DEFAULT' inserted on Ctrl+a+Backspace

As said before, the ngModel directive uses @Input and correspondingly the ngOnChanges() hook to fetch any changes to the value from <input> tag. One important thing to note is ngOnChanges() won't be triggered if the value hasn't changed(1).

We could try to split the two-way binding [(ngModel)] to [ngModel] input and (ngModelChange) output.

export class AppComponent {
  public testString: string;

  onChange(value: string) {
    this.testString = value === '' ? 'DEFAULT' : value;
  }
}
<input type="text" [ngModel]="testString" (ngModelChange)="onChange($event)" />

Still error prone: Stackblitz

Here the Ctrl+a+Backspace any string other than 'DEFAULT' would insert 'DEFAULT' as expected. But Ctrl+a+Backspace 'DEFAULT' would result in empty <input> box due the ngOnChanges() issue discussed above.


Solution

One way to achieve expected behavior is to not depend on the ngModel directive's ngOnChanges() hook to set the value, but to do it ourselves manually. For that we could use an Angular template reference variable in the <input> and send it to the component for further manipulation.

export class AppComponent {
  public testString: string;

  public onChange(value: string, inputElem: HTMLInputElement) {
    this.testString = value === '' ? 'DEFAULT' : value;
    inputElem.value = this.testString;
  }
}
<input
  type="text"
  #myInput
  ngModel
  (ngModelChange)="onChange($event, myInput)"
/>

Working example: Stackblitz

Here the #myInput is the template reference variable. If this feels hacky, you'd need to know using ngModel to manipulate <input> is in itself called template driven forms. And it's quite legal to manipulate the template ref directly.

With all that said, IMO in cases where such input manipulation is needed, I'd recommend you to use the Angular Reactive Forms instead. It provides a more granular control over the input.


(1) The ngOnChanges() won't be triggered if the previousValue and currentValue of the respective @Input variable's SimpleChange object hasn't changed.

over 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error