Friday, March 9, 2018

Switching from Template Driven, to Reactive or Model Driven Forms

When we started writing Angular 2 apps, we had come from an AngularJS background. So of course our first forms were template driven. All we had to change from AngularJS was ng-model to ngModel and put it in a banana box. As long as the form's validation remains simple, Template driven forms are probably the way to go primarily due to their simplicity. However as the complexity of the forms grows, especially the validation of the form, its readability and even feasibility go bad pretty quickly. The only other downside to template driven forms is that they can't be unit tested. In our company most of these sorts of things were tested at an end-to-end level using Gherkin anyway, so less of an issue for us. But again as the complexity grows you might need to start unit testing those edge cases.

So let's take a relatively straightforward concrete example where the validation requirements might force us into implementing them in Reactive or Model-Driven forms. One side note about the nomenclature, we try to use Model Driven in our company, because we have React projects as well, and things can get pretty confusing distinguishing between a React form and a Reactive form. The example we are going to look at is a change password form. The validation requirements are that the passwords are strong, and that they match.

First let's take a look at the Template Driven HTML (change-password.component.html)

Change Password

{{error}}

And here is the TypeScript (change-password.component.ts)

export class ChangePasswordComponent {
  formErrors: string[];

  oldPassword: string;
  newPassword: string;
  confirmNewPassword: string;

  constructor() { }

  changePassword() {
    // submit to server
    if (this.newPassword!==this.confirmNewPassword){
      this.formErrors=["Passwords don't match"];
    } else {
      this.formErrors=[];
    }
  }
}

So far no validation. It *is* possible to write template validation using directives, but it is much simpler using Model-driven forms. To convert over the first thing we need to remember is to add the ReactiveFormsModule to your module (app.module.ts)

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
and
imports:[
 BrowserModule, FormsModule, ReactiveFormsModule

Then at the top of your component (change-password.component.ts) you will need to add:

import { FormBuilder, FormGroup } from '@angular/forms';

In the fields section of your component replace

  oldPassword: string;
  newPassword: string;
  confirmNewPassword: string;
with
  form: FormGroup;

Lastly, change the constructor to this:

constructor (protected formBuilder: FormBuilder) {
  this.form=formBuilder.group({
    oldPassword:[''],
    newPassword:[''],
    confirmNewPassword:['']
  });
}

So basically there is one field where there use to be three, but the constructor was expanded to initialize the form with those three values. Now let's change the HTML (change-password.component.html). First find the form element, and change

  
to
  

Lastly, change all banana in a boxed ngModels, e.g. [(ngModel)] to formControlName. Here is an example change:

        
to
        

After doing that for all 3 fields. Voila! it is converted.

In Part 2 I will talk about the validation.

PS: For some reason Blogger and/or SyntaxHighlighter hate Angular code, it might be easier to read this over on my BrainHz blog

40 comments:

  1. It Is the best crack software website for all Mac and Windows users around the world.
    ARTICULATE STORYLINE

    ReplyDelete

  2. Uninstalling CyberLink software permanently removes the application from your computer. Below you uninstall, you should: ... Not attempt to manually uninstall or remove CyberLink software by dragging folders to the Recycle Bin. Doing so can cause irreversible problems when you try to reinstall the product.
    Click this LINK

    ReplyDelete
  3. This impressed me so much amazing. Keep working and providing information
    activator

    ReplyDelete
  4. hi sir,i’d love to share this posting with the readers on my site. thanks for sharing this blogvmix crack

    ReplyDelete
  5. hi Dear, Thank you for sharing your details and experience. I think it very good for me. Keep it up! Also May you like TopCrackWindows

    ReplyDelete
  6. MKVToolnix Crack is an amazing POST with good content.FINDCRACK is the best crack software site for all Mac and Windows users all over the world.

    ReplyDelete
  7. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
    Wondershare Filmora Keygen

    ReplyDelete
  8. Avast Antivirus Crack is an internet security suite of cross-platform applications developed by Avast for Microsoft Windows, macOS, Android, and iOS.
    windowsloader.org


    ReplyDelete
  9. Dear, I am for the first time, and I found beneficial information. Very nice and well-explained article. Thanks for sharing. Iris Pro Serial Key

    ReplyDelete
  10. PC Crack
    Thank you for reading,
    I hope this post was useful to you.
    I appreciate you sharing such an informative and interesting post.
    License Cracked

    ReplyDelete
  11. It Is the best crack software website for all Mac and Windows users around the world.
    BandiZip serial key

    ReplyDelete
  12. I think F-Secure Freedome VPN is a fantastic Post with great content. CRACKDUE is the best cracked software site for all Mac and Windows users throughout the world.

    ReplyDelete

  13. Good Post. This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you.
    Driver Easy Crack torrent

    ReplyDelete
  14. It’s great and fantastic piece. Keep it up as I look forward to read more from this website.
    DVDFab Crack

    ReplyDelete
  15. I think Edraw Crack is a great Post with very good content. CRACKDUE is the best crack software site for all Mac and Windows users.

    ReplyDelete
  16. This was really a fascinating matter, I am very lucky to have the ability to come to your blog and
    I will bookmark this page so that I might come back one other time.
    Lumion 11 Pro Crack

    ReplyDelete
  17. .Global Mapper Crack . is a great Post with useful information and great content. CRACK GURU is the most popular crack software website for Mac users and Windows users worldwide.

    ReplyDelete

  18. Thanks for reading,
    This post was hopefully helpful to you.
    Your post was interesting and informative, so thanks for sharing.
    Isobuster crack

    ReplyDelete
  19. NCH Pixillion Image Converter Plus Crack . is a great Post with useful information and great content. CRACK GURU is the most popular crack software website for Mac users and Windows users worldwide.

    ReplyDelete
  20. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
    Mirillis Action activation key

    ReplyDelete
  21. It is the most popular crack software website for Mac users and Windows users worldwide.
    UCRACKS

    ReplyDelete
  22. thank you giving us a great info about this blog. keep it up for good work. cracksco

    ReplyDelete


  23. it has a simple and easy to use interface. I've been using it for a long time and it is the best one indeed. Thanks for post this blog,is magnificent software for greater results of your task.
    Musify Layest version

    ReplyDelete
  24. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!autocad 2017 crack

    ReplyDelete
  25. Hi, I have to say I am impressed. I rarely come across such an informative and interesting blog,
    and let me tell you that you nailed it. Windows 11 can be activated with this code.

    ReplyDelete
  26. It’s great and fantastic piece. Keep it up as I look forward to read more from this website.
    Adobe Photoshop

    ReplyDelete
  27. Potential causes of hair loss in teenagers include genetic factors, hormonal imbalances, and underlying medical conditions. In some cases, hair loss can be reversible with proper treatment.

    auslogicsbostspeed crack

    ReplyDelete
  28. This is a widespread and quite normal situation.licensecracked

    ReplyDelete
  29. VECTOR MAGIC CRACK content and information on the Post are excellent. For Mac and Windows users worldwide, This Site WELL CRACK is the best crack software website.

    ReplyDelete
  30. PASSFAB FOR RAR CRACK content and information on the Post are excellent. For Mac and Windows users worldwide,

    ReplyDelete
  31. Your article is very impressive, when I was going through the article I found you mention something that I was searching for a very long time. So, thanks for sharing. Create a Lyft Account

    ReplyDelete
  32. microsoft office 2016 crack
    Microsoft Office 2016 is type of MS Office which help the users to write, modify and present the document.

    ReplyDelete
  33. This comment has been removed by the author.

    ReplyDelete