Handle user input using Reactive Forms in Angular
Three steps to use the form controls:
1. Register reactive forms module in your application.
Import ReactiveFormsModule from the angular forms library.
2. Generate a new FormControl
To generate a Form Control, create a new component, and then create a new instance of the FormControl.
Use the command to create the component: ng generate component UserInput
A new component folder must be created after executing the above command. Now open the component user-input.component.ts.
Now bind the FormControl instance to the view element using formControl binding provided by FormControlDirective.
Now, Any change in the textbox (view element) updates the form control model, and changes in the model will update the view as well.
user-input.component.ts
import { Component, OnInit } from '@angular/core';
import {FormControl} from '@angular/forms'
@Component({
selector: 'app-user-input',
templateUrl: './user-input.component.html',
styleUrls: ['./user-input.component.css']
})
export class UserInputComponent {
firstName = new FormControl('')
lastName = new FormControl('')
}
user-input.component.html
<label> First Name :</label>
<input class="form-control" type="text" [formControl]="firstName" />
<label> Last Name:</label>
<input class="form-control" type="text" [formControl]="lastName" />
<hr>
<div> <b>User Details: </b> <br/>
<label>First Name : </label> {{ firstName.value }} <br/>
<label>Last Name : </label> {{ lastName.value }}
</div>
Now, in the root component template, call the user-input.component.ts using its selector "app-user-input".
app.component.html
<app-user-input> </app-user-input>
Open the browser, and see the output:
0 Comments