Given, an input for a street address.
<input
id="street"
name="street"
#street="ngModel"
[(ngModel)]="address.street"
(ngModelChange)="onPropertyChange($event, street)"
required
minLength="1"
placeholder="Enter Street Here"
type="text"
/>
In the last article we showed the proper pattern for NgModel configuration as shown above.
Today we focus on ngModelChange.
#street="ngModel"
[(ngModel)]="address.street"
(ngModelChange)=
"onPropertyChange($event, street)"
The triad of #street, ngModel and ngModelChange allows us to crack open the ngModel internals. onPropertyChange handler shows us the ngModel.
onPropertyChange($event, street: ngModel) {
debugger;
}
What's interesting is that the "$event" variable shows us the current change; however; the "street" variable has far more information because it is the "NgModel". We don't need the $event
The NgModel contains the automatically created FormControl, the model, and viewModel, and the name of the "element". Other properties are present which other articles will discuss.
The changes are easily seen using...
Model and ViewModel
// the change to be made
let change = ngModel.viewModel;
// the prior value
let prior = ngModel.model;
Valid Yet?
// use the ngModel valid function
let valid = ngModel.control.valid;
Caution
The id attribute isn't strictly necessary and would cause issues if this control is reused in the same page.
Refactored Version
No id or $event...
<input
name="street"
#street="ngModel"
[(ngModel)]="address.street"
(ngModelChange)="onPropertyChange(street)"
required
minLength="1"
placeholder="Enter Street Here"
type="text"
/>
Conclusion
When NgModel is used like this, the use of explicit Form Groups and Form Controls are not needed any longer. It's a disruption to Reactive forms and forms.
JWP2020 NgModel Internals
Top comments (0)