(change) vs (ngModelChange) in Angular

ctrl/m
0

Have you ever encountered code where something you expected to work didn't resolve as you had imagined? 🤔 ALMOST ALL THE TIME LOL!!!! 

So today I was monitoring event changes in the DOM using (change) and [(ngModel)]. What I did not realize is that I needed to

  1. Monitor the Angular event of the [(ngModel)] and not the DOM input event
  2. (change) listens to the changes of the <input> event on the DOM
  3. (ngModelChange) is what I needed
Let's say, for example, you need to monitor the change of a variable in your component and trigger an event on an input field when that variable changes. If you are like me and have never used (ngModelChanges) Angular event to this date of writing, you can waste lots of hours trying to find the right workaround. But the solution is just there in the documentation

Enough talk, show me the code!!!

[(ngModel)] is what will decide what we get to use, and also our intent will decide whether to use (ngModelChange) or (change). 

Be careful also when using radios and checkboxes

Depending on the kind of element being changed and the way the user interacts with the element, the change event fires at a different moment:

template: `
<input [(ngModel)]="bar">
`,
})
export class App {
name = 'Angular';
bar = 'Chocolate';
}


What is the purpose of (ngModelChange) and how is it different from (change)?

@Component({
selector: 'app-root',
standalone: true,
imports: [FormsModule],
template: `
<input [value]="domBar" (change)=updateDOMBar($event)>
<h2>DOM-Change {{domBar}}</h2>

<input [value]="domBar" (input)=updateDOMBar($event)>
<h2>DOM-Input {{domBar}}</h2>

<input [(ngModel)]="ngBar" (ngModelChange)=updateAngularBar($event)/>
<h2>NG- {{ngBar}}</h2>
`,
})
export class App {
ngBar = 'Chocolate';
domBar = 'Chocolate';

updateAngularBar($event: any) {
this.ngBar = $event;
}

updateDOMBar($event: any) {
this.domBar = $event.target.value;
}
}



Thus: (change) will only fire when the user has blurred the input, pressed the enter key, or selected values from a list of options 
(ngModelChange)  will fire every time an element changes


SHALOM! 

#Angular #WebDevelopment #CodingTips #TechTips #Programming #Code #Developer #SoftwareEngineering
Tags:

Post a Comment

0Comments

Post a Comment (0)