Have you ever encountered code where something you expected to work didn't resolve as you had imagined? 🤔 ALMOST ALL THE TIME LOL!!!!
- Monitor the Angular event of the [(ngModel)] and not the DOM input event
- (change) listens to the changes of the <input> event on the DOM
- (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
[(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:
- When a
<input type="checkbox">
element is checked or unchecked (by clicking or using the keyboard);- When a
<input type="radio">
element is checked (but not when unchecked);
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