Angular Basics-10

Welcome to part-10 of Angular Basics series. In this part , we will learn about Reactive approach to create forms in Angular.

The starting point can be taken from here.

We have a simple html form in the project, which we are going to change into Angular reactive approach.

The first thing we will do is to change the FormsModule to ReactiveFormsModule in app.module.ts file.

Now in app.component.ts file we will add the signupForm and then in ngOnInit add the username, email and gender.

We also have an onSubmit to console log the signupForm.

Now, in app.component.html file add the formGroup, ngSubmit and formControlName and we are done.

Now, in localhost when we add values and submit the form, we will get the values.

Now, we will add validators in our project and for this first in app.component.ts file, add Validators in FormControl.

Next, in app.component.html file, we will add get methods to check whether the username or email is valid.

Now, in app.component.css file we will add the class to show the red border on error.

Now, our validations are working perfectly on localhost.

Now, we will complete our form by getting the default values in it, by using the setValue in ngOnInit. We are also resetting the form after the user submits it.

Our app is complete now and the default values are been selected and the reset also working properly. The code for the same can be taken from this github repo.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nabendu Biswas

Nabendu Biswas

590 Followers

Founder TWD, JavaScript & ReactJS Trainer, Youtuber, Blogger