In my last post we already created a form for our email form to be sent via a PHP backend. This form is created based on this explanations:

This post will show also a different way of working with forms, when you need a little bit more flexibility.

To start quickly from the beginning, we have in simple ways this html form:

We have here two inputs for email and password and a login button. In the form we specified the submit event to be executed by the doLogin method. Both input have the ngControl tag and are bind to a property of the model object. the email input has also the local variable email which is set by ngForm to be able show or hide a div depending if the input is valid or not.

And here is the component:

Here is the working plunk of this simple example:


So, before going to the next step. Let’s extend this example a little bit. We will hide the form and show a message that the login was successful. See here this working plunk:


So now, lets extend our example with a different approach. We will control the controls & validators from our component, not from the html.

We will need to inject FormBuilder, Validators & Control from angular2/common. Then in our constructor we create with the FormBuilder our two controls (email & password), assigning a default value and our validators. Password has just the required validator, but in the email, we created our own, which checks if there is a word called magic, if so, then it is invalid, otherwise valid. It is not much different than before huh? but this gives us more flexibility with our validators and showing some messages on the screen. Check out the html:

The first div, we are using it as before. But the second two div’s are using now our own validator, to show a message when it is valid or not. Pretty cool huh?

Here is the working plunk:

Angular2 Forms

Also published on Medium.

Tagged on:     

Leave a Reply


Get every new post on this blog delivered to your Inbox.

Join other followers:

Welcome Damir Kusar

Log in

Lost your password?
%d bloggers like this: