loading...
Cover image for Angular NgModel Internals for Input Element

Angular NgModel Internals for Input Element

jwp profile image John Peters Updated on ・2 min read

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

Posted on by:

jwp profile

John Peters

@jwp

Lit-Html or Svelte?

Discussion

pic
Editor guide