How to Read Formgroup Options in Java
Angular FormGroup Example
July 21, 2020
This page will walk through Angular FormGroup case. The FormGroup takes part in creating reactive form. FormGroup is used with FormControl and FormArray. The role of FormGroup is to track the value and validation state of form control. In our example we will create a grade that volition include <input> and <select> element. We will see how to instantiate FormGroup and how to set and admission values in FormGroup. We volition too validate the class. Commencement let us empathise the angular classes and directive that we will employ in our example.
FormControl:Information technology is a class that tracks the value and validation country of a course control.
FormGroup: It is a class that tracks the value and validity state of a group of FormControl.
FormArray: Information technology is a grade that tracks the value and validity state of assortment of FormControl, FormGroup and FormArray.
FormControlName: It is a directive that syncs a FormControl in an existing FormGroup to a form command by name.
FormGroupDirective: It is a directive that binds an existing FormGroup to a DOM element.
FormGroupName: Information technology is a directive that syncs a nested FormGroup to a DOM chemical element.
FormArrayName: It is a directive that syncs a nested FormArray to a DOM element.
Now we will talk over the complete example step by step.
Contents
- Technologies Used
- Using FormGroup
- FormGroup setValue() and patchValue()
- FormGroup reset()
- FormGroup valueChanges() and statusChanges()
- FormGroup with Radio Button
- FormGroup with Select Chemical element
- FormGroup Validation
- Nested FormGroup
- Nested FormArray
- Complete Example
- Run Application
- References
- Download Source Code
Technologies Used
Find the technologies being used in our example.
1. Angular 10.0.0
2. Node.js 12.five.0
iii. NPM 6.9.0
Using FormGroup
To use a FormGroup, find the post-obit steps.
Stride-1: Import ReactiveFormsModule from @angular/forms library in our awarding module and configure ReactiveFormsModule in imports metadata of @NgModule as following.
import { NgModule } from '@angular/cadre'; import { ReactiveFormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], ------------- ------------- }) export class AppModule { } ReactiveFormsModule enables using FormControl, FormGroup and FormArray in our application.
Step-ii: Create an case of FormGroup with the instances of FormControl.
userForm = new FormGroup({ proper name: new FormControl(), age: new FormControl('xx') }); If we desire to initialize a default value, we tin pass information technology every bit an argument in FormControl. In the above code age form command volition be pre-populated with the value 20.
Step-3: Now we create a <form> element in our HTML template. The selector of FormGroupDirective is [formGroup]. We will demark FormGroup instance userForm with the selector [formGroup] and FormControl instances are spring to form command using FormControlName directive. At present find the code.
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> Proper name: <input formControlName="proper name" placeholder="Enter Name"> Age: <input formControlName="age" placeholder="Enter Age"> <push button type="submit">Submit</push button> </class>
When we click on submit button, grade volition exist submitted and ngSubmit will telephone call our method onFormSubmit.
Step-4: Create a method that will be called when form is submitted.
onFormSubmit(): void { panel.log('Name:' + this.userForm.get('name').value); } FormGroup setValue() and patchValue()
setValue() and patchValue() both are used to prepare values to FormGroup case at run fourth dimension. The difference between them is that when nosotros apply setValue(), nosotros have to fix all form controls in our FormGroup and when we use patchValue() so selected form control can be set up. Find the case.
Suppose we are creating FormGroup every bit post-obit.
userForm = new FormGroup({ name: new FormControl(), age: new FormControl() }); i. Using setValue()
this.userForm.setValue({proper noun: 'Mahesh', age: 'twenty' }); It is necessary to mention all from controls in setValue() otherwise it will throw mistake.
2. Using patchValue()
this.userForm.patchValue({proper noun: 'Mahesh'}); When nosotros use patchValue() so it is non necessary to mention all grade controls.
FormGroup Get Value
Suppose userForm is the instance of FormGroup. To get the value of form control named equally name after form submit, we need to write the code as below.
this.userForm.get('name').value If nosotros want to get all values of the form then nosotros can write code every bit given beneath.
FormGroup reset()
To reset the form we need to phone call reset() method on FormGroup instance. Suppose userForm is the instance of FormGroup and then we create a method equally given below.
resetForm() { this.userForm.reset(); } We tin call the in a higher place method using a push button as following.
<button blazon="push button" (click) = "resetForm()">Reset</button>
If nosotros desire to reset form with some default values, then assign the default values with grade control proper name of the form.
resetForm() { userForm.reset({ name: 'Mahesh', age: twenty }); } FormGroup valueChanges() and statusChanges()
To runway the value changes and status changes of a form control we need to listen them using subscribe() method. Observe the lawmaking.
usrNameChanges: cord; usrNameStatus: cord; ngAfterViewInit(): void { this.userForm.get('name').valueChanges.subscribe(data => this.usrNameChanges = data); this.userForm.go('proper name').statusChanges.subscribe(data => this.usrNameStatus = data); } In the above code name is the name of class control. Now nosotros can utilize value changes and status changes to display on UI.
<p *ngIf="usrNameChanges">Proper noun: <b>{{usrNameChanges}}</b> </p> <p *ngIf="usrNameStatus">Proper name Status: <b>{{usrNameStatus}}</b> </p> FormGroup with Radio Button
To use radio push button in a FormGroup, first we will create an instance of FormControl within a FormGroup.
userForm = new FormGroup({ -------------- -------------- gender: new FormControl('male') }); We are creating radio push button to select gender while filling the course. We can pass the initial value while instantiating FormControl. Now we will create the grade in HTML template equally given below.
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> --------------------------- --------------------------- <div> Select Gender: <input type="radio" formControlName="gender" value="male person"> Male <input blazon="radio" formControlName="gender" value="female person" > Female person </div> </form>
Nosotros tin access its value using get() method.
this.userForm.get('gender').value FormGroup with Select Element
Here nosotros will provide how to employ select element with FormGroup. First of all we will create an array of elements that will contain central and value for select chemical element. Find the array given below.
profiles = [ {name: 'Developer', shortName: 'dev'}, {name: 'Manager', shortName: 'human'}, {name: 'Manager', shortName: 'dir'} ]; We volition use the value of proper name in our array to display data in select element and the value of shortName volition be assigned to value attribute of <option> element.
Now to use select element in a FormGroup, first we will create an instance of FormControl within a FormGroup.
userForm = new FormGroup({ -------------- -------------- profile: new FormControl(this.profiles[0].shortName) }); We tin can pass the initial selected value while instantiating FormControl. In the above code kickoff element of array profiles will be selected equally default. Now we will create the form in HTML template every bit given below.
<div> Select Profile: <select formControlName="profile"> <option *ngFor="let pf of profiles" [ngValue]="pf.shortName"> {{ pf.name }} </option> </select> </div> We tin access its value using get() method.
this.userForm.go('contour').value; FormGroup Validation
To validate a form command in FormGroup, angular provides Validators form. We can apply information technology to enable validation in form command as given below.
userForm = new FormGroup({ name: new FormControl('', [Validators.required, Validators.maxLength(10)]), age: new FormControl('', Validators.required) }); To check validity of course command, we can write a method for a course control as given below.
get userName(): any { return this.userForm.get('name'); } Now in HTML template we can admission validity state as userName.invalid. Nosotros tin can also get validity state straight using instance of FormGroup.
userForm.become('historic period').invalid Now discover the sample HTML template code of form.
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <div> Name: <input formControlName="name" placeholder="Enter Name"> <label *ngIf="userName.invalid" [ngClass] = "'error'"> Name is required with 10 max graphic symbol. </label> </div> <div> Age: <input formControlName="age" placeholder="Enter Age"> <label *ngIf="userForm.get('age').invalid" [ngClass] = "'fault'"> Age is required. </characterization> </div> <div> <button blazon="submit">Submit</push> </div> </form> If nosotros want to disable a field with pre-populated value, we tin can instantiate form control equally given beneath.
land: new FormControl({value: 'India', disabled: true}) Nested FormGroup
A FormGroup instance tin can contain a nested FormGroup instance. The apply of nested FormGroup is that if we want to go validity land of just few course controls and not all, then nosotros can put those form controls in a nested FormGroup every bit given beneath.
userForm = new FormGroup({ name: new FormControl('', [Validators.required, Validators.maxLength(10)]), accost: new FormGroup({ houseNumber: new FormControl('', Validators.required), city: new FormControl('Noida') }) }); In the higher up code address is the nested FormGroup inside userForm FormGroup. To utilise nested FormGroup in course element in HTML template, angular provides FormGroupName directive that syncs a nested FormGroup to a DOM element. Find the lawmaking.
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <div> Name: <input formControlName="name" placeholder="Enter Name"> <label *ngIf="userName.invalid" [ngClass] = "'error'"> Name is required with 10 max character. </label> </div> <div formGroupName="address"> <div> House Number: <input formControlName="houseNumber" placeholder="Enter Firm Number"> <label *ngIf="userForm.get('address').get('houseNumber').invalid" [ngClass] = "'error'"> House Number is required. </label> </div> <div> Metropolis: <input formControlName="city" placeholder="Enter City"> </div> <div> Country: <input formControlName="country"> </div> </div> <div> <push type="submit">Submit</button> </div> </form> Go value of nested FormGroup
Outset we demand to get nested FormGroup by parent FormGroup and call the get() method.
let addressFG = this.userForm.get('accost'); addressFG.get('houseNumber').value; Notice the code snippet to get the value and validity state of a nested FormGroup.
addressFG.value addressFG.valid
Set value in nested FormGroup
To ready the value in course controls of nested FormGroup, we tin write the code every bit given below.
setCountry() { this.userForm.get('accost').get('country').setValue('India'); } setDefaultValue() { this.userForm.patchValue({name: 'Mahesh', address: {city:'Noida', land: 'India'} }); } Nested FormArray
FormArray is used to add and remove class elements at runtime. We can use a FormArray inside a FormGroup as given below.
userForm = new FormGroup({ proper name: new FormControl('', [Validators.required, Validators.maxLength(10)]), users: new FormArray([ new FormControl('Mahesh'), new FormControl() ]) }); We volition write code in grade as given beneath.
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <div> Name: <input formControlName="proper name" placeholder="Enter Name"> <label *ngIf="userName.invalid" [ngClass] = "'error'"> Name is required with 10 max grapheme. </characterization> </div> <div formArrayName="users"> <div *ngFor="let user of users.controls; index as idx"> <input [formControlName]="idx" placeholder="Enter User Name"> <button type="button" (click)="deleteUserField(idx)">Delete</button> </div> </div> <push type="button" (click)="addUserField()">Add More than User</button> <button type="submit">Submit</button> </form>
To add together form controls in FormArray at runtime, the instance of FormArray will call button() method that accepts new case of FormControl and to remove class control, it will telephone call removeAt() method that accepts index of form control to exist removed. We can write the methods as given below.
addUserField() { this.users.push button(new FormControl()); } deleteUserField(index: number) { this.users.removeAt(index); } On the submit of course, we can admission the values of private class control of FormArray as given below.
for(permit i = 0; i < this.users.length; i++) { console.log(this.users.at(i).value); } To become the value and validity state of FormArray, we tin write lawmaking as given below.
this.userForm.value this.userForm.valid
Complete Instance
formgroup.component.ts
import { Component, AfterViewInit } from '@angular/core'; import {FormControl, FormGroup, FormArray, Validators} from '@angular/forms'; @Component({ selector: 'app-form-group', templateUrl: 'formgroup.component.html', styleUrls: ['formgroup.component.css'] }) export course FormGroupDemoComponent implements AfterViewInit { usrNameChanges: string; usrNameStatus: string; formSubmitted = false; profiles = [ {proper name: 'Developer', shortName: 'dev'}, {proper noun: 'Manager', shortName: 'man'}, {proper noun: 'Director', shortName: 'dir'} ]; userForm = new FormGroup({ name: new FormControl('', [Validators.required, Validators.maxLength(x)]), age: new FormControl('', Validators.required), accost: new FormGroup({ houseNumber: new FormControl('', Validators.required), city: new FormControl('Noida'), land: new FormControl({value: 'India', disabled: true}) }), gender: new FormControl('male'), profile: new FormControl(this.profiles[one].shortName), users: new FormArray([ new FormControl('Mahesh'), new FormControl('Krishna'), new FormControl() ]) }); get userName(): any { return this.userForm.go('name'); } ngAfterViewInit(): void { this.userForm.go('proper name').valueChanges.subscribe(data => this.usrNameChanges = information); this.userForm.get('proper name').statusChanges.subscribe(information => this.usrNameStatus = data); } onFormSubmit(): void { this.formSubmitted = true; if(this.userForm.valid) { this.logData(); this.resetForm(); } else { this.formSubmitted = false; } } resetForm() { this.userForm.reset(); } setDefaultValue() { this.userForm.patchValue({name: 'Mahesh', gender: 'male', profile: this.profiles[ii].shortName, address: {city:'Noida', country: 'Republic of india'} }); } setAge() { this.userForm.get('age').setValue('xx'); } setCountry() { this.userForm.get('address').become('country').setValue('India'); } get users(): FormArray { return this.userForm.go('users') as FormArray; } addUserField() { this.users.push(new FormControl()); } deleteUserField(index: number) { this.users.removeAt(index); } logData() { panel.log('Name:' + this.userForm.go('name').value); panel.log('Age:' + this.userForm.get('age').value); console.log('Gender:'+ this.userForm.get('gender').value); panel.log('Profile:'+this.userForm.get('profile').value); //print address permit addressFG = this.userForm.go('accost'); console.log('House Number: ' + addressFG.get('houseNumber').value); panel.log('Urban center:' + addressFG.get('city').value); console.log('Country:' + addressFG.go('country').value); //Iterate FormArray for(let i = 0; i < this.users.length; i++) { console.log(this.users.at(i).value); } // Gives complete address console.log(addressFG.value); //Checks address validation console.log(addressFG.valid); // Gives consummate FormArray data panel.log(this.users.value); //Checks FormArray validation console.log(this.users.valid); // Gives Complete form information panel.log(this.userForm.value); // checks Complete form validation panel.log(this.userForm.valid); } } formgroup.component.html
<h3> FormGroup Example </h3> <div *ngIf="userForm.invalid && !formSubmitted" [ngClass] = "'fault'"> Form not validated. </div> <div *ngIf="formSubmitted" [ngClass] = "'success'"> Class submitted successfully. </div> <br/> <div> <grade [formGroup]="userForm" (ngSubmit)="onFormSubmit()"> <div> Name: <input formControlName="name" placeholder="Enter Name"> <label *ngIf="userName.invalid" [ngClass] = "'error'"> Name is required with 10 max graphic symbol. </label> </div> <div> Age: <input formControlName="age" placeholder="Enter Age"> <label *ngIf="userForm.become('age').invalid" [ngClass] = "'mistake'"> Age is required. </label> </div> <div formGroupName="address"> <div> House Number: <input formControlName="houseNumber" placeholder="Enter House Number"> <characterization *ngIf="userForm.get('accost').get('houseNumber').invalid" [ngClass] = "'error'"> Business firm Number is required. </characterization> </div> <div> Urban center: <input formControlName="city" placeholder="Enter Metropolis"> </div> <div> Country: <input formControlName="country"> </div> </div> <div> Select Gender: <input type="radio" formControlName="gender" value="male person"> Male <input type="radio" formControlName="gender" value="female" > Female </div> <div> Select Profile: <select formControlName="contour"> <option *ngFor="let pf of profiles" [ngValue]="pf.shortName"> {{ pf.proper noun }} </option> </select> </div> <br/> <div formArrayName="users"> <div *ngFor="let user of users.controls; index as idx"> <input [formControlName]="idx" placeholder="Enter User Proper noun"> <button type="push" (click)="deleteUserField(idx)">Delete</button> </div> </div> <button type="button" (click)="addUserField()">Add together More than User</button> <br/><br/> <div> <button type="submit">Submit</button> <button type="button" (click) = "setAge()">Set Historic period</push button> <button type="button" (click) = "setCountry()">Ready State</button> <button blazon="button" (click) = "setDefaultValue()">Set up Defaults</push button> <push type="button" (click) = "resetForm()">Reset to Bare</push button> </div> </form> <div> <p *ngIf="usrNameChanges">Name: <b>{{usrNameChanges}}</b> </p> <p *ngIf="usrNameStatus">Name Status: <b>{{usrNameStatus}}</b> </p> formgroup.component.css
.error{ colour: reddish; font-size: 20px; } .success{ color: green; font-size: 20px; } app.component.ts
import { Component } from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; @Component({ selector: 'app-root', template: ` <app-form-group></app-form-group> ` }) consign class AppComponent { } app.module.ts
import { NgModule } from '@athwart/core'; import { ReactiveFormsModule } from '@athwart/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { FormGroupDemoComponent } from './formgroup.component'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], declarations: [ AppComponent, FormGroupDemoComponent ], bootstrap: [ AppComponent ] }) consign grade AppModule { } Run Application
To run the awarding, find following steps.
ane. Download source lawmaking using download link given below on this page.
2. Use downloaded src in your angular CLI application. To install angular CLI, find the link.
3. Run ng serve using control prompt.
iv. Now access the URL http://localhost:4200
Find the impress screen of the output.
References
FormControl
FormGroup
FormArray
Download Source Lawmaking
Source: https://www.concretepage.com/angular-2/angular-2-formgroup-example
Post a Comment for "How to Read Formgroup Options in Java"