DEV Community

Cover image for Angular NgModel Validation
John Peters
John Peters

Posted on • Edited on

Angular NgModel Validation

Our prior series on Angular Validation discussed Form Group and Form Control validation. The negative aspect of using them is the immutability requirements. The fact that two way binding now needs to be done in our code is well, it's ridiculous in my opinion. Let's look into a more user friendly option, the NgModel.

NgModel



 <select
    id="city"
    name="city"
    [ngModel]="address.city"
    #city="ngModel"
    [pattern]="onGetCity(city)"
 >
      <option>Select City</option>
      <option *ngFor="let city of address.cities">
         {{ city.name }}
      </option>
</select>



Enter fullscreen mode Exit fullscreen mode

Our code above shows use of the ngModel for an address.city name. The id, name and #city attributes are straight out of the angular text book. Use this pattern and two-way binding with validation is ready to go!

Notice the [pattern] binding. We put this in originally to find out why our html side regex patterns weren't working. Much to our surprise we finally (accidentally) cracked open the ngModel internals.

NgModel Structure

When hooking up [ngModel]='some.property' have you ever wondered more about how ngModel works?

Alt Text

The NgModel contains

  • A FormControl
  • A field for the Model
  • An update EventEmitter
  • A valueAccessor
  • A viewModel

And other deeper stuff.

Summary: There's no reason to use Form Controls when NgModel uses them internally. In future articles we'll dive in a bit deeper.

JWP ngmodel NgModel

Top comments (0)