What are the differences between template driven forms and reactive forms in angular 2 - angular2-forms

In angular 2 what is the difference between the template driven forms and reactive form. In which situations we need to use the template driven forms and reactive forms

Simply we can say
Reactive form can be used in the following situation
Complex forms with more number of fields.
Multiple complex validation are there. Custom validations are required
Require JSON structure to be send with the values in the form.
We can get entire form in a structured way by using "form.value"
If we have 4 fields First Name, Last Name, Email, Phone Number in reactive form.
HTML code will be
<form [formGroup]="form">
First Name <input formControlName="firstName">
Last Name <input formControlName="lastName">
Email <input formControlName="email">
Phone Number <input formControlName="phoneNumber">
</form>
We can get the values from the form like below
{
"firstName": "FName",
"lastName": "LName",
"email": "test#123.com",
"phoneNumber": "123"
}
by calling form.value, where form is FormGroup Variable that we created.
Template Driven Form :
It can be used when using simple forms. Like login page.
With the two way data binding. We can simply assign value to variable from ui and vice versa.
Simple example is if we are givng two way binding for the below input.
<input [(ngModel)]="username">
We can simply display the value that user is giving in the UI.
<p>Hello {{username}}!</p>

A comprehensive answer to a similar question can be found here:
What are the practical differences between template-driven and reactive forms?
here is what Aravind is posted which is abstract and direct to the point. so I copy and paste the entire comparison:
Template Driven Forms Features
Easy to use
Suitable for simple scenarios and fails for complex scenarios
Similar to AngularJS
Two way data binding(using [(NgModel)] syntax)
Minimal component
Automatic track of the form and its data(handled by Angular)
Unit testing is another challenge
Reactive Forms Features
More flexible, but needs a lot of practice
Handles any complex scenarios
No data binding is done (immutable data model preferred by most
developers)
More component code and less HTML markup
Reactive transformations can be made possible such as
Handling a event based on a debounce time
Handling events when the components are distinct until changed
Adding elements dynamically
Easier unit testing
A side by side pros and cons

With the template driven approach you basically apply directives, such as ngModel, in your template. Based on these directives Angular will create formcontrol objects. This approach is good for building simple forms with basic validation (required, minlength, maxlength,...).
With the reactive approach you basically need to create new instances of the formcontrols and formcontrolgroups in your component. Reactive forms are also the best choice for building more complex forms and are better in case you have the intention to implement unit testing for your forms.
Checkout the following topic...
http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
Angular2 Forms API, Template driven or Reactive?

Related

Is a Binder the only way to have automatic handling for a data-entry field being required in Vaadin 8 layout?

In Vaadin 8, the BinderBuilder::asRequired lets us define a Binder where a field is known to be required on a layout. If data is missing, the layout indicates to the user that the field needs to have data entered. This is great functionality, and smartly designed.
But using a Binder can be overkill for very small forms or dialog boxes. For one thing, we must define a data class to interact with the binder which can seem silly for a little form.
➙ Is there any other way to tap into Vaadin’s automatic handling of a required field without using a Binder?
In the Community Articles section of the manual, there is a page, Mark required fields as such. That page shows TextField as having setRequired and setRequiredError methods. But this seems incorrect. I can find no such methods on the latest TextField JavaDoc.
But using a Binder can be overkill for very small forms or dialog boxes. For one thing, we must define a data class to interact with the binder which can seem silly for a little form.
Yes. This is somewhat true. Thus I implemented FieldBinder tool. Which makes possible to use similar validator - converter chain as with Binder (it replicates the same API for applicable parts) with single field without Bean. Also it has the same facilities to handle validation status changes, uses same way to show required value, or validation error as Binder.
https://vaadin.com/directory/component/fieldbinder

Reading Form Post data vs strongly typed View

I have a set of HTML pages containg input elements. I am in the process of converting them into MVC Views.
Considering performance & cleanliness of code. What is the correct way to proceed,
Processing Form as posted FormCollection, or
Create Strongly typed view to obtain input values from the Model.
One advantage of using HTML helpers is it enables better compile-time checking of your views (allowing you to find errors at build-time instead of at runtime), and also supports richer intellisense when editing your view templates within Visual Studio.
Another advantage might be HTML helpers allows you to set any custom attributes on the HTML tag. You can do that with the helper by either passing in a dictionary or using an anonymous type like following.
#Html.TextArea("FirstName", Model.FirstName, new { parameter = "value" });
Source 1
Source 2
You can use an overload of TextBoxFor to set/override the input element attributes:
#Html.TextBoxFor(m => m.Name, new { #Value = "0", readonly="readonly" #class="cssClass"})
This is actually a good question..I don't know who voted it down...there are too many strict view model evangelists in my opinion.
After Having worked with MVC for awhile my view is that for very simple things the #Html helpers work very well...however they lead to a way of thinking about the webpage/server interaction that is limiting in the long run, especially for more complicated uses. It lets you rely heavily on unobtrusive validation without having to understand how validation works on the client..this is great for the introductory programmer...as I once was...however not understanding at least the jquery validation libraries will handicap you eventually. Doing any serious web/web-application development where validation is more complicated than checking if a value is required becomes much more diffucult. In addition you are relying on Microsoft to keep their validation library in sync with the jquery validation libraries should you update them(I've ran into this issue).
In addition you need to consider what if any front-end libraries you are using and if any of them don't work well with the output of these helpers(bootstrap is one notable one). That being said form collection is faster and less restrictive...using it and the pure validation libraries will be easier and more expressive...letting you write whatever code you want. After all..how hard is it to write if(!String.IsNullorEmpty()) on the server-side or whatever type of validation you need in addition to the client.

Page initialization patterns with ASP.NET MVC and MVVM like knockoutjs

When creating an interactive form or other kind of web page, there are a couple of options with knockoutjs. One could create a strongly-typed view and pass a model to it from a controller. On the other hand, one could just as easily start with a plain old html document, and have it initialize itself by calling action methods (JsonResult or otherwise) after the initial load.
Also when starting out the page as an MVC view, you could use HtmlHelpers along with plain old html markup to initialize the view. Another option is to serialize the model state as json to a hidden field, and use that to initialize the view.
In my experience, during first load, there can be a delay when you let ko initialize the view. Whether you construct a viewmodel by passing json from a serialized hidden field, or rely on it to invoke various services to load the data, there is a moment before the page is "ready". These kinds of delays can be avoided by initializing the page with HtmlHelpers, etc, but such initialization could also incur additional costs (extra initialization logic in the controller, default content in the views, etc).
Which way of initializing a page is the most MVVM? Is it a bad idea to use HtmlHelpers in the views, or to use cshtml at all? If not, where do you draw the line between view and viewmodel?
"The most MVVM" is a hard question to answer, especially considering that we are already mixing patterns with MVC and Knockout.
I would think that letting Knockout do all the work of initilization would be "the most MVVM", but rigid adherance to a pattern when you are having issues is not a good idea. If KO setting values after the DOM is ready causes problems that you can fix by letting the HtmlHelpers initialize the page, then do what works. Since the HtmlHelpers will let you set the data-bind attributes at the same time, this feels like a good solution, and I have done this before with good results.
I would say that storing JSON in a hidden field is not a good idea though. You can directly encode your model into JSON by using this in your javascript:
var initialData = #Html.Raw(Json.Encode(Model));
This is a good solution since the page starts out with the data your controller sends it, without needing a second request.
You may have to think about what trade-offs you want to make. If you want purity and no code duplication, you might have to accept the issue of KO taking a little time to initialize the page. If you want a perfect User Experience, you may have to sacrifice a little purity.

ASP.NET MVC 2 Custom Model Binding Question

Background
I have a payment page where the user can select from a list of existing payment methods, or specify a new one. The dropdown presents options such as:
Visa - ******1234 (Saved)
Mastercard - ******9876 (Saved)
[New Credit Card ...]
[New Electronic Check ...]
Using jQuery, I toggle hidden DIVs that contain either an informational table (in the case of options 1 or 2 for saved payment methods) or a form (in the case of the [new] options).
I am using a strongly typed class as my view model which contains (among simple types) a CreditCard class and a Check class. Each of these classes uses data annotation validators, as they are used in other parts of the site.
Problem
The problem comes in when the user submits the form. I would like to use model binding to handle the mapping of POST values, but I need the binding and/or validation to fire depending on which option the user selected. For example, if the user selects option 1 or 2 from the list above, I don't want the model validation (or maybe even the binding itself) to fire for the CreditCard or Check objects.
I have researched the possibilities of creating a custom model binder using IModelBinder as well as extending the DefaultModelBinder and just overriding some of the methods. However, I am unsure as to which method is better, and, if extending DefaultModelBinder, which would be the appropriate method to override.
The logic would be fairly simple:
If the user selected one of the existing payment methods, no validation on the CreditCard or Check are required.
If the user selected one of the options to create a new payment method, then only the selected method (CreditCard or Check) needs to be bound and validated
It feels as if extending the DefaultModelBinder is the way to go, as I would like most of the heavy lifting to be done by the framework without the need to create a custom binder from scratch. However, when looking at the available methods to override, it's not clear which is the best one(s):
BindProperty - The problem here is that I basically need to look at one of the properties to determine what other properties should be bound. I don't think I can control the order in which the incoming properties are bound, and I wouldn't want to rely on the order they are set in the HTML form.
OnModelUpdated - By this point, it's too late. The binding validation from the data annotations has been triggered and the ModelState has been updated. I would have to loop through the ModelState and remove the errors that are not relevant.
OnPropertyValidating - At first I thought this is where I should look, but even returning TRUE for all properties (as a test) causes the ModelState to contain binding errors.
I have come across this scenario in other aspects of the application and decided to split up functionality into separate controller/actions to simplify the process. However, I would like to have a better understanding of how to approach more complex UI problems, particularly related to the MVC model binding features.
Any help on this subject would be greatly appreciated.
All the possible values are stored in a dropdown list. Using jQuery, I toggle the form (for a new payment method) and the display (for an existing method)
I have decided to try to circumvent model binding altogether and use FormCollection, IValueProvider, and TryUpdateModel inside my controller action.
Your issue sounds way to specialized to be placed in the default ModelBinder.
The ModelBinder is this seductress that lures you in on the pretense that she can solve all of your problems. But then you start merging ModelState's together and going off to do crazy things with nested objects lists and before you know it she slaps you with divorce papers and takes everything but your bones.
MVC 3 holds some promise to provide a more extensible ModelBinder but from my own personal experience unless its super simple what you need to change, such as empty texboxes becoming "" instead of null, than stay clear away from your own implementation.
The alternative approach is to use the existing ModelBinder functionality piecemeal and using things like Ignore method parameters to clean things up:
if( myModel.IsNewPayment )
UpdateModel( myModel.Payment, "exclude everything else" );
A lot of what your proposing to stuff into the model binder is really business logic too that should be in another layer. I've done some crazy things with my own ModelBinder and now regret every line of code I've written in there. Maybe its just me but your really bending the rules and completely trashing the "single responsibility principal" by putting business and payment logic in there.

Suggested approach to generate pages based on attributes on properties in model in ASP.Net MVC!

We need to generate forms for Create/Display/Edit on our website. The requirement is that these need to be metadata driven. We will have properties on our Model attributed with the type of control to generate for that property.
[RenderAs("DatePicker", Order = 1)]
public DateTime DateOfBirth{get; set;}
The idea is to have templates for each of these like Date-Picker.ascx, etc in the SharedFolder
We need to generate around 25 such forms and are looking for a reuseable way of accomplishing this. What would be the best way to handle validations with this (basic validations like required, less than, greater than, etc)? What do you suggest for dependent field validations (less than field, greater than field)? Does this sound sensible?
Thanks
It sounds like you're looking for MVC 2 templates.
Use DisplayForModel for read only views and EditorForModel for create/edit forms built from the metadata in your view model. Use Data Annotations attributes to decorate the view model with validation rules and other rendering information (label, custom template to use, etc.).
Here's a quick intro video to MVC 2 templates.
Check out ASP.Net Dynamic Data. It is pretty much what you are looking for. (And if you can use .Net 4.0 then you should be able to use MVC, webforms, and DynamicData all in one project.)
You are mixing Model and View concept. Why do you need MVC THEN?
On practice, you will face situations when Admin need some minor changes compared to regular user, and it will be hard to support in cases when form is generated using attributes.
I am not saying this is best, but we decided to stick with form concept and every form able to decide WHAT to show and HOW to show.
And we defined number of helper methods like RenderDatePicker which do all dirty work.

Resources