Angular : Using the NgModel for forms. Template Driven Forms
If you been search on form handling when using Angular you might have herd Reactive Forms VS Template Driven Forms. Many people would say that Reactive Forms are better and you should just use them over Template Driven Forms. And while I will not argue against that notation. I do not believe this means that the NgModel should just be completely ignored. Its a simple to understand and read way that you could easily get a form up and running. So lets jump in
First thing is first, we gotta make sure to import form module into our angular app.
Lets start with a basic form of course
We got three very basic form fields, now we need to hook this up to the TypeScript to get ready to ship off. So lets start by creating some variables.
Now we got our Vars created lets hook it up inside the HTML
Here we use [(ngModel)] to wire up to the variable’s we created, a important when using the ngModel is that we have to put a “name” attribute as well. I always just put the name the same as the ngmodel. I also added a button that runs a function when clicked, sendData(). Now lets create that function get our variables ready to send off too.
That’s it! We are all wired up and put all the data in a object ready to be shipped off to where ever. Lets fire up the app, put in some random test data and click the submit button to see what we get in the console.
That’s it, simple right? There disadvantages and advantages to creating forms like this and I will go deeper into these subjects but this was to just give a basic idea on how to user the ngmodel for forms.
Connect with me on linkedIn: www.linkedin.com/in/joshua-markasky47
follow me on Twitter: https://twitter.com/MarkaskyJ
Checkout my YouTube channel: https://www.youtube.com/channel/UCgRkJcniRghYpSpzKQlEYvQ