DEV Community

Cover image for Angular Forms and Reactive Forms
John Peters
John Peters

Posted on • Updated on

Angular Forms and Reactive Forms

Over the past year, I've come to the conclusion that explicit Angular Form and Reactive Forms coding may almost completely be replaced as follows:

Forms and Reactive Forms

When we choose these constructs we are saddled with ton's of messy boiler-plate code. As well as implementing two-way binding within our code.

This indicates a problem with the implementation of these two types of validation coding. We should have known from the start that all this boiler plate work is a bad code smell. What used to work is now, in my mind considered deprecated!

Try ngModel instead

We get all the goodness of automatically created form controls using the ngModel as outlined in the article above. No more boiler plate code.

Become familiar with the triad of ngModel way of doing things and it's simple to use.

  • Add a #controlName parameter and assign it a ngModel value
#controlName = "ngModel"

Enter fullscreen mode Exit fullscreen mode
  • Use two way binding syntax for the ngModel, where propertyName is found in your Typescript code.
[(ngModel)] = 'propertyName'
Enter fullscreen mode Exit fullscreen mode
  • Hook up a change event handler like this.
(ngModelChange)='propertyName = onPropertyChanged(controlName);
Enter fullscreen mode Exit fullscreen mode
  • In onPropertyChange return the viewmodel.
onPropertyChanged(ngModel){
 // can spin off asynchronous task here
 // the viewModle property is always the proposed change
 return ngModel.viewModel;
}
Enter fullscreen mode Exit fullscreen mode

As the article points out Pipes work too, they are the last thing to fire and do not create another round of changes!

Oh yes, the formBuilder and the formControl array concepts are history too.

Alt Text

Caveat: If you need to detect if all of the models are valid, ngModel doesn't provide that. In that case use Forms and Reactive Forms.

JWP2020 FormControls aren't Dead

Top comments (0)