Angular guid

Better UX better code with angular reactive forms

Reactive forms

Yurii K
Quick Code

--

We all fill forms for a different reasons. It is hard imagine our life without form. You want to register on this site fill form, you want to attend the concert fill form e.t.c.

Angular has some very handy tools which we could use when we are creating forms.

Let’s create a simple registration form with two inputs and one submit button.

Simple form

At line 5 we define a name of the form (userlogin) and submit action handler (onClickSubmit). ‘onClickSubmit’ is a method which defined in component which takes a form value. In this method we can verify passed data and show error if they not valid. Also every input has an attribute ‘ngModel’, it is very important without it our form will work not properly.

FormsModule must be declared in ‘imports’ section in our ‘AppModule’.

FormsModule on line 17

We don’t want to send on server empty data, we must check them.

Method ‘onClickSubmit’

Verify data in inputs is not a good solution. Instead of doing it lets see what we could use in ‘ReactiveFormsModule’. In this model we will find a couple of handy tools.

First we need to add this module in ‘import’ section in ‘AppModule’.

ReactiveFormsModule on line 18

After that we need to create another form.

Another form

Every field has own formControlName. All fields in this form must be filled instead of check every property, let’s disable submit button if form not valid.

Sometimes we need to check the data on several conditions. In the constructor of Angular ‘FormControl’ we can pass an array of validators.

Validators are set up

If the user has filled the input with incorrect data we must say about it.

Label with messages

Every input has a label which will be shown if user filled input with incorrect data. FormGroup ‘userInfo’ has an array of the controls. Property ‘touched’ tell us when user interacted with input if we don’t use this property in ‘if’ condition user will see this message before he did something. Property ‘invalid’ tell us when data is not valid.

Result

If you need to take a close look on project here is the link.

Originally published at http://tomorrowmeannever.wordpress.com on June 22, 2019.

--

--

Yurii K
Quick Code

Full-stack developer. In my work, I use Angular and C#. In my free time I write articles for my blog.