0

How to detect input field value changes immediately without pressing enter button in angular ?

I was trying to trigger a function on a value change of input field in Angular. Initially I used Keypress event, that was detecting the insertion the input field correctly, but even I used backspace to remove any character from the value, it didn't trigger that function, which means that these changes went unnoticed. I was expecting that it would trigger that event on the each change or update of the value.

1
  • Can you provide some code or a stackblitz? Commented Jan 13, 2023 at 6:57

3 Answers 3

2

Using Input


In HTML

<input (input)="type($event)" type="text" />

In TS

 type(event) {
    console.log(event.target.value);
  }

Using ngModel


In HTML

<input type="text" [ngModel]="mymodel" (ngModelChange)="valuechange($event)" />

In TS

mymodel:any
        
 valuechange(newValue) {
   this.mymodel = newValue;
   console.log(newValue)
 }

Demo Link :- Link

Sign up to request clarification or add additional context in comments.

2 Comments

It's more "Angular way" use [(ngModel)]. This "two ways binding" allow give value to a variable declare in .ts
i have just added it's code also @Eliseo
1

you can use [(ngModel)]. I suggest you "split" the "bannana sintax"

<input matInput placeholder="Word" 
          [ngModel]="search" 
          (ngModelChange)="search=$event;doSomething($event)">

doSomething(value:string)
{
    console.log(value)
}

Another ways can be

<!--see that the event "input" return a "generic event"
    so you use $event.target.value to "reach" the value-->
<input matInput placeholder="Word" 
          [(ngModel)]="search" 
          (input)="doSomething($event.target.value)">

Or

<input matInput placeholder="Word" 
          [(ngModel)]="search" 
          (ngModelChange)="doSomething($event)">

Comments

0

By using two-binding and ngModelChange event, worked for me to detect all changes. Sample code :

     <input matInput placeholder="Word"
       [(ngModel)]="search"
       (ngModelChange)="filterTbl()"
       matTooltip="Filter Result">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.