Forms in Angular

Let's try to summarize the most blatant shortages of our current form-less approach:

  • We cannot keep track of the global form state, there's no way we can tell whether the form is valid or not, if some required fields are missing and so on
  • We have no easy way to display error messages to the user to let them know what they have to do to make the form valid
  • We do not verify the input data, we just collect them into objects, and then serialize and toss them to the server without thinking twice

Sure, we can easily work around most of these issues by implementing some custom methods within our form-based components; we can throw some isValid(), isNumber() and so on here and there, and then hook them up to our template syntax and show/hide the validation messages with the help of *ngIf, *ngFor, and the likes. However, it will definitely be a horrible way to address our problem; we didn't choose a feature-rich client-side framework such as Angular to work that way.

Luckily enough, we have no reason to do that, since Angular provides us with a couple of alternative strategies to deal with these common form-related scenarios: Template-Driven Forms and Model-Driven (or Reactive) Forms. Both of them are thigh-coupled with the framework and thus extremely viable; they both belong to the @angular/forms library and also share a common set of form control classes. However, they also have their own specific sets of features, along with their pros and cons, that can ultimately lead us to choose one of them. Let's try to quickly summarize these differences.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.133.180