How to work Multiple select fields & Radio buttons in Reactive Forms Angular 6/7 with Validation

  Angular

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.

To use reactive forms, import ReactiveFormsModule from the @angular/forms package and add it to your NgModule’s imports array.

app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }

Generate a component for the control using angular cli

ng g c component-name

The FormControl , FormGroup class is the basic building block when using reactive forms. To register a single form control, import the FormControl class into your component and create a new instance of the form control to save as a class property.


import { Component, OnInit } from '@angular/core';
import { Validators, FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['./registration.component.css']})
export class RegistrationComponent implements OnInit {

countries:any;
states:any;
indexies:any;
years:any;
filings:any;
quarters:any;
userForm :FormGroup;
submitted= false;
constructor() {

this.userForm = new FormGroup({
'country' : new FormControl('',Validators.required),
'option' : new FormControl('index'),
'index':new FormControl('',Validators.required),
'state' : new FormControl({value:'', disabled : true},Validators.required),
'year': new FormControl('',Validators.required),
'filing': new FormControl('',Validators.required),
'option2': new FormControl('quarter'),
'quarter': new FormControl('',Validators.required),
'process': new FormControl('option2')

})

}

index(){
return this.userForm.get('index');
}
get year(){
return this.userForm.get('year');
}
get filing(){
return this.userForm.get('filing');
}
get quarter(){
return this.userForm.get('quarter');
}
ngOnInit() {

this.countries = [
{'id':'2','name':'USA'},
{'id':'1','name':'India'},
{'id':'4','name':'Canada'},
{'id':'6','name':'China'},
{'id':'3','name':'Singapore'}
];
this.states = [
{'id':'1','name':'Karnataka'},
{'id':'2','name':'Tamilnadu'},
{'id':'3','name':'Andra'},
{'id':'4','name':'kerala'},
{'id':'5','name':'J&K'},
{'id':'6','name':'MP'}
];
this.indexies =[
{"id" :1, "name": "US S&P 500 "},
{"id" :2, "name": "IND S&P 500"},
{"id" :3, "name": "CAN S&P 500"},
];
this.years = [2019,2018,2017,2016,2015,2014,2013];
this.filings =[
{"id" :1, "name": "US S&P 500 "},
{"id" :2, "name": "IND S&P 500"},
{"id" :3, "name": "CAN S&P 500"},
];
this.quarters =[
{"id" :1, "name": "Q1"},
{"id" :2, "name": "Q2"},
{"id" :3, "name": "Q3"},
{"id" :3, "name": "Q4"}
];
}


indexDataset(x){
if (x==1){
this.userForm.controls['state'].disable();
this.userForm.controls['index'].enable();
}
else {
this.userForm.controls['index'].disable();
this.userForm.controls['state'].enable();
}
}
Quarter(x){
if(x==1){
this.userForm.controls['quarter'].disable();

}else{

this.userForm.controls['quarter'].enable();
}
}


}

Add the form controls and design in component html file. Here we have a multiple select field and radio button.

Create a property in the component class named userForm and set the property to a new form group instance. To initialize the form group, provide the constructor with an object of named keys mapped to their control.

Note that just as a form group contains a group of controls, the userForm FormGroup is bound to the form element with the FormGroup directive, creating a communication layer between the model and the form containing the inputs. The formControlName input provided by the FormControlName directive binds each individual input to the form control defined in FormGroup. The form controls communicate with their respective elements. 

component.html (using bootstrap 4)

<div class="container mt-2">
<h2 align="center">Data Process</h2>
<hr>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<div class="form-row">

<div class="form-group col-md-3">
<label for="inputEmail4">Country</label>
<select formControlName="country" class="form-control">
<option value="">Choose Country</option>
<option *ngFor="let country of countries" value="{{country.id}}">{{country.name}}</option>
</select>
<div *ngIf="(submitted || country.touched )&& country.invalid" class="alert alert-danger" >
<div *ngIf="country.errors.required">* Country Required</div>

</div>
</div>
<div class="col-md-3">

<div class="form-check form-check-inline col-sm-5">
<input class="form-check-input" type="radio" name="" (click)="indexDataset(1)" formControlName="option" id="" value="index" >
<label class="form-check-label" for="inlineRadio1">Index</label>
</div>
<div class="form-check form-check-inline col-sm-5">
<input class="form-check-input" type="radio" name="" (click)="indexDataset(2)" formControlName="option" id="" value="state">
<label class="form-check-label" for="inlineRadio2">State</label>
</div>
</div>


<div class="form-group col-md-3" >
<label for="inputPassword4">Dataset</label>
<select formControlName="index" class="form-control" id="dataset" >
<option value="">Choose Dataset</option>
<option *ngFor="let index of indexies" value="{{index.id}}">{{index.name}}</option>
</select>
<div *ngIf="(submitted || index.touched )&& index.invalid" class="alert alert-danger" >
<div *ngIf="index.errors.required">* Dataset Required</div>

</div>
</div>


<div class="form-group col-md-3">
<label for="inputPassword4">State</label>
<select formControlName="state" class="form-control" id="state" >
<option value="">Choose State</option>
<option *ngFor="let state of states" value="{{state.id}}">{{state.name}}</option>
</select>
<!-- <div *ngIf="(submitted || state.touched )&& state.invalid" class="alert alert-danger" >
<div *ngIf="state.errors.required">* State Required</div>
</div> -->
</div>

</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputPassword4">Years</label>
<select formControlName="year" class="form-control" >
<option value="">Choose Years</option>
<option *ngFor="let year of years" value="{{year}}">{{year}}</option>
</select>
<div *ngIf="(submitted || year.touched ) && year.invalid" class="alert alert-danger" >
<div *ngIf="year.errors.required">* Year Required</div>

</div>
</div>
<div class="form-group col-md-3">
<label for="inputPassword4">Filings</label>
<select formControlName="filing" class="form-control" >
<option value="">Choose Years</option>
<option *ngFor="let file of filings" value="{{file.id}}">{{file.name}}</option>
</select>
<div *ngIf="(submitted || filing.touched )&& filing.invalid" class="alert alert-danger" >
<div *ngIf="filing.errors.required">* Filings Required</div>

</div>
</div>

<div class="form-group col-md-3">

<div class="form-check form-check-inline col-sm-5">
<input class="form-check-input" type="radio" name="" (click)="Quarter(1)" formControlName="option2" id="" value="anual" >
<label class="form-check-label" for="inlineRadio1">Anual</label>
</div>
<div class="form-check form-check-inline col-sm-5">
<input class="form-check-input" type="radio" name="" (click)="Quarter(2)" formControlName="option2" id="" value="quarter">
<label class="form-check-label" for="inlineRadio2">Quarter</label>
</div>
</div>

<div class="form-group col-md-3">
<label for="inputPassword4">Quarter</label>
<select formControlName="quarter" class="form-control" id="qty">
<option value="">Choose Quarter</option>
<option *ngFor="let quart of quarters" value="{{quart.id}}">{{quart.name}}</option>
</select>
<div *ngIf="(submitted || quarter.touched ) && quarter.invalid" class="alert alert-danger" >
<div *ngIf="quarter.errors.required">* Quarter Required</div>

</div>
</div>

</div>


<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" formControlName="process" name="" id="" value="option1" checked>
<label class="form-check-label" for="exampleRadios1">
ARM
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" formControlName="process" name="" id="" value="option2">
<label class="form-check-label" for="exampleRadios2">
MRM
</label>
</div>
<div class="form-check disabled">
<input class="form-check-input" type="radio" formControlName="process" name="" id="" value="option3" >
<label class="form-check-label" for="exampleRadios3">
Auto Extract
</label>

</div>

</div>


<button type="submit" class="btn btn-primary">Sign in</button>
<div ><pre>{{userForm.value | json}} </pre></div>
</form>
</div

In this form we added validation also but if you want validation on click submit button please add this code. check the html page we provide in if condition submitted  form then validation will work

onSubmit() {
this.submitted = true;

// stop here if form is invalid
if (this.userForm.invalid) {
return;
}
else{
alert('Success');
return;
}
}

Note: Use these HTML5 validation attributes in combination with the built-in validators provided by Angular’s reactive forms. Using these in combination prevents errors when the expression is changed after the template has been checked.

Spread the Code

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of