2
votes

I am using Angular2. I want to do form validations. Currently my template looks like this:

<form #f="ngForm" novalidate (ngSubmit)="save()">
        <input type="checkbox" name="showHydroSystemSelection" [(ngModel)]="cosResponse.showHydroSystemSelection.value" (ngModelChange)="onChange(cosResponse.showHydroSystemSelection.shouldRefresh)"/>
        <label>System Selection</label>
        <select name="systemSelection" id="systemSelection" [(ngModel)]="cosResponse.systemSelection.selected" (ngModelChange)="onChange(cosResponse.systemSelection.shouldRefresh)">
            <option *ngFor="let option of cosResponse.systemSelection.value" value="{{option.id}}" >
            {{option.name}}
            </option>
        </select>

</form>

In many blogs on how to do angular2 validations, they say to use a formGroup on the form. But if I do that, then angular complains with the error: " ngModel cannot be used to register form controls with a parent formGroup directive. Try using formGroup's partner directive "formControlName" instead"

The syntax for using ngModel is very good and dynamic for our app which totally depends on metadata to render different elements. The formGroup as a model is too explicit and static for our needs. I don't understand what are these two ways of using the model, and how to use formGroup effectively and as easily as ngModel

1

1 Answers

0
votes

You are correct @vanval!

I think that it´s a discussion about code, strategy and user experience.

In summary we change for template-driven approach which is more easy to work with it, to reactive (in model-driven approach) for giving us more control, that results in a better testable form by leveraging a decoupling between the HTML (design/CSS team can work here) and component's business rules (angular/js specialist members) and to improve the user experience with features like reactive transformations, correlated validations and handle complex scenarios as runtime validation rules and dynamic fields duplication.

This article is a good reference about it: Angular 2 Forms - Template Driven and Model Driven Approaches