Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular state not updating until click anywhere

Very new to Angular, and just trying to get a feel for it. I have an input component:

import { Component } from '@angular/core';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
})
export class InputComponent {
  q = '';

  queryChange(value: string) {
    this.q = value;
  }
}

It’s html:

<div>
  <input #query type="text" (change)="queryChange(query.value)" />
  <button>Search</button>
  <div>{{ q }}</div>
</div>

When I type into the input, the {{ q }} doesn’t update until I click anywhere on the screen, or hit enter. Almost like refocusing. Coming from React I’m confused as to why this happens with the Angular’s (change) rather than updating as I type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My first thought was that maybe because I’m passing the value of the input to queryChange(query.value) instead of passing the event value like I would usually do in React.

>Solution :

I think the problem is about the DOM and not Angular. You should use (input) instead of (change) if you want the event to trigger every time you type.

<input #query type="text" (input)="queryChange(query.value)" />

See this StackBlitz, as well as change and input MDN references. Specifically, MDN says about change:

Unlike the input event, the change event is not necessarily fired for each alteration to an element’s value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading