DEV Community

Cover image for Angular NgModel Internals for Input Element
John Peters
John Peters

Posted on • Updated on

Angular NgModel Internals for Input Element

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"
 />
Enter fullscreen mode Exit fullscreen mode

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)"
Enter fullscreen mode Exit fullscreen mode

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;       
   }
Enter fullscreen mode Exit fullscreen mode

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

NgModel
Alt Text

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;
Enter fullscreen mode Exit fullscreen mode

Valid Yet?

// use the ngModel valid function
let valid = ngModel.control.valid;
Enter fullscreen mode Exit fullscreen mode

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"
 />
Enter fullscreen mode Exit fullscreen mode

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)