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

54 comments:

  1. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic

    Hadoop training institutes in chennai | Big data Hadoop Certification in chennai | Hadoop Training in Velachery | Hadoop Training in OMR | Hadoop Training with Placements

    ReplyDelete
    Replies
    1. Big data is a term that describes the large volume of data – both structured and unstructured – that inundates a business on a day-to-day basis. big data projects for students But it’s not the amount of data that’s important.Project Center in Chennai

      Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.

      Spring Training in Chennai

      The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete

  2. Get the most advanced Python Course by Professional expert. Just attend a FREE Demo session.
    For further details call us @ 9884412301 | 9600112302
    Python training in chennai | Python training in velachery

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

    ReplyDelete

  4. 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
  5. This impressed me so much amazing. Keep working and providing information
    activator

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

    ReplyDelete
  7. 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
  8. Dear, I have recently started a website, the info you provide on this site has helped me greatly. Thank you for all of your time & work. Format Factory Pro Crack

    ReplyDelete
  9. 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
  10. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
    Wondershare Filmora Keygen

    ReplyDelete
  11. 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
  12. 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
  13. I’m glad that you just shared this helpful info with us. Please keep us informed like this
    FileZilla Pro

    ReplyDelete
  14. 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
  15. It Is the best crack software website for all Mac and Windows users around the world.
    BandiZip serial key

    ReplyDelete
  16. 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

  17. 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
  18. It’s great and fantastic piece. Keep it up as I look forward to read more from this website.
    DVDFab Crack

    ReplyDelete
  19. 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
  20. 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
  21. I Considered UTorrent Pro Crack is an excellent Post with very good content. CRACK GURU is the best crack software site for both Mac and Windows users.

    ReplyDelete
  22. .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

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

    ReplyDelete
  24. 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
  25. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!
    Mirillis Action activation key

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

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

    ReplyDelete
  28. FlyVPN Crack is an excellent Post with Amazing content. All Mac and Windows users can download crack software from this KEYGENBRO site.

    ReplyDelete


  29. 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
  30. Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!autocad 2017 crack

    ReplyDelete
  31. 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

  32. hi sir,Found your post interesting to read. I cant wait to see your post soon. Good Luck for the upcoming update.This article is really very interesting and effective thank you.
    Directory Monitor Pro Crack

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

    ReplyDelete
  34. 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
  35. This is a widespread and quite normal situation.licensecracked

    ReplyDelete
  36. 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
  37. PASSFAB FOR RAR CRACK content and information on the Post are excellent. For Mac and Windows users worldwide,

    ReplyDelete
  38. It was a very good post indeed. I thoroughly enjoyed reading it in my lunch time. Will surely come and visit this blog more often. Thanks for sharing. download mathcad 15 full crack

    ReplyDelete
  39. Thank you for writing such an interesting blog. Please add some more relevant topics to the conversation. We've come to read your blog because there's no other purpose for us to be here, as you well know. Well, if you get time, you must checkout my website DedicatedHosting4u.com

    ReplyDelete

  40. Thanks for Sharing such an amazing article. Keep working... Your Site is very nice, and it's very helping us.. this post is unique and interesting, thank you for sharing this awesome information Simple Disable Key Crack

    ReplyDelete
  41. Windows 10 Activator Extreme is a tool that locates manufacture and retail keys in many servers for Windows 10 with a broad range of scatterings. Bit by bit, the Keys are regularly recovered.
    Windows 10 Activator
    windows 11 activator
    Windows 7 Ultimate Product Key
    windows 8.1 product key

    ReplyDelete
  42. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for the informative post. download vMix

    ReplyDelete