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"
- Use two way binding syntax for the ngModel, where propertyName is found in your Typescript code.
[(ngModel)] = 'propertyName'
- Hook up a change event handler like this.
(ngModelChange)='propertyName = onPropertyChanged(controlName);
- In onPropertyChange return the viewmodel.
onPropertyChanged(ngModel){
// can spin off asynchronous task here
// the viewModle property is always the proposed change
return ngModel.viewModel;
}
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.
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)