Creating form in Angular 8
The angular reactive form is used to handle the user's input. We can use Angular form in the application to authorize the user to log in, to update profile, to enter information, and to perform many other data-entry tasks.
In Angular 8, there are two approaches to handle the user's input by forms.
- Reactive forms
- Template-driven forms
Both are used to collect user input events from the view, validate the user input, create a form model and model to update, and provide a way to track changes.
Angular 8 Form Example
Here, we understand the angular 8 form example. We use Angular reactive form.
The steps are given below:
- Create an Angular form app named angular8from and run the server by using the following commands.
ng new angular8form
Then,
cd angular8form ng serve
- Install bootstrap 4 using the following command.
npm install bootstrap --save
- Now, include the bootstrap four in the angular.json file into the style array in the angular project.
"styles": [ "./node_modules/bootstrap/dist/CSS/bootstrap.min.css", "src/styles.css" ],
- Register the Reactive forms Module
Use the reactive forms by importing ReactiveFormsModule from @angular/forms package and add it into the app.module.ts file's import array.
We use the given below code in “app.module.ts” file.
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent], }) export class AppModule { }
- Add FormControl class register to the control in the template and update the FormControl value.
The FormControl class is the essential building block of angular when using reactive forms. So if we want to record the single form control, we need to import the FormControl class into our component and create the new instance of the form of control to save as the class property.
Now, modify the “app.component.ts” file.
// app.component.ts import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { email = new FormControl(''); updateEmail() { this.email.setValue('tutorial&[email protected]'); } }
Also, update the view in app.component.html file.
Value:{{email.value}}
Now, we can start the server to see the output.
Enter any email, and we will see the result in the value.
When we click on the "Update Email" button, it will update the email id as we saved in the template file.