Monday, October 12, 2020

Radio Button in Angular Form Example

In this post we’ll see how to use radio buttons in Angular form. We’ll see examples of adding radio button to both template-driven and reactive form in Angular.


Radio button in template driven form example

In this Angular template driven form example we’ll have a form with two input fields for name and email, a date picker for picking date and a group of radio buttons to select membership type.

Data Model (member.model.ts)

Member class defines the data model reflected in the form.

export class Member {
  name: string;
  mail: string;
  membershipDate: Date;
  membershipType: string;
  constructor(name: string, mail: string, membershipDate: Date, membershipType: string) {
    this.name = name;
    this.mail = mail;
    this.membershipDate  = membershipDate;
    this.membershipType = membershipType;
  }
}

Template (app.component.html)

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8">
      <h1>Membership Form</h1>
      <form (ngSubmit)="onSubmit()" #membershipForm="ngForm">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" 
            id="name"
            ngModel name="name">                        
        </div>
        <div class="form-group">
          <label for="email">email</label>
          <input type="email" class="form-control" 
            id="email"
            ngModel name="email">                        
        </div>
        <div class="form-group">
          <label for="mdate">Membership Date</label>
          <input type="date" class="form-control" id="mdate"
            [ngModel]="currentDate | date:'yyyy-MM-dd'"  name="mdate">                        
        </div>
        <div class="form-group">
          <label>Membership Type</label>
          <div class="radio" *ngFor="let mtype of membershiptypes">
            <label for="type">
              <input type="radio" name="type"
                ngModel [value]="mtype">
              {{mtype}}
            </label>
          </div>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form> 
    </div>
  </div>
  <hr>
  <div *ngIf="submitted">
    <div class="row">
      <div class="col-xs-12 col-sm-10 col-md-8">
        <p>Name: {{member.name}}</p>
        <p>email: {{member.mail}}</p>
        <p>Membership Date: {{member.membershipDate | date:'dd/MM/yyyy'}}</p>
        <p>Membership Type: {{member.membershipType}}</p>
      </div>
    </div>
  </div>  
</div>
  1. For radio button options are added using ngFor which iterates over an array called membershiptyes defined in the Component class.
  2. class="radio" is a Bootstrap class added for styling.
  3. ngModel is placed to indicate that this element is a form control.
  4. [value]="mtype"sets the value of the button to one of the values in each iteration.
  5. {{mtype}} displays the associated text with each button.
  6. If you want one of the button to be selected by default then you can use one way binding with ngModel.
    <input type="radio" name="type"
                    [ngModel]="defaultMemberType" [value]="mtype">
    	
    defaultMemberType is defined in the Component class with one of the values.
    defaultMemberType="Silver"
    

Component class (app.component.ts)

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Member } from './member.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  @ViewChild('membershipForm') memberForm : NgForm;
  membershiptypes = ['Silver', 'Gold', 'Platinum'];
  currentDate = new Date();
  //defaultMemberType="Silver"
  member = new Member('', '', new Date(), '');
  submitted = false;

  onSubmit(){
    this.submitted = true;
    this.member.name = this.memberForm.value.name;
    this.member.mail = this.memberForm.value.email;
    this.member.membershipDate = this.memberForm.value.mdate;
    this.member.membershipType = this.memberForm.value.type; 
  }
}

Radio button in reactive form example

With reactive form creation of FormGroup and FormControl is done explicitly in the Component class (Type script code). If we are creating the same form as done in template driven from then the component class looks like as given below.

app.component.ts

import { DatePipe } from '@angular/common';
import { Component, OnInit} from '@angular/core';
import { FormControl, FormGroup} from '@angular/forms';
import { Member } from './member.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
  providers: [DatePipe]
})
export class AppComponent implements OnInit {
  membershiptypes = ['Silver', 'Gold', 'Platinum'];
  currentDate = new Date();
  member = new Member('', '', new Date(), '');
  submitted = false;
  membershipForm : FormGroup;
  constructor(private datePipe: DatePipe){ }
  ngOnInit() {
    this.membershipForm = new FormGroup({
      memberName: new FormControl(null),
      email: new FormControl(null),
      mdate: new FormControl(this.datePipe.transform(this.currentDate, 'yyyy-MM-dd')),
      membershipType: new FormControl('Silver')
    });
  }
  onSubmit(){
    this.submitted = true;
    this.member.name = this.membershipForm.value.memberName;
    this.member.mail = this.membershipForm.value.email;
    this.member.membershipDate = this.membershipForm.value.mdate;
    this.member.membershipType = this.membershipForm.value.membershipType; 
  }
}

If you see in the Component class we don’t have to do any thing special for Radio button, form control is added for Membership type like any other FormControl. A default value is also passed with it.

Template (app.component.html)

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8">
      <h1>Membership Form</h1>
      <form [formGroup]="membershipForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" id="name"
                 formControlName="memberName">                        
        </div>
        <div class="form-group">
          <label for="email">email</label>
          <input type="email" class="form-control" id="email"
          formControlName="email">                        
        </div>
        <div class="form-group">
          <label for="mdate">Membership Date</label>
          <input type="date" class="form-control" id="mdate"
          formControlName="mdate">                        
        </div>
        <div class="form-group">
          <label>Membership Type</label>
            <div class="radio" *ngFor="let mtype of membershiptypes">
              <label for="type">
                <input type="radio"
                formControlName="membershipType" [value]="mtype">
                {{mtype}}
              </label>
            </div>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form> 
    </div>
  </div>
  <hr>
  <div *ngIf="submitted">
    <div class="row">
      <div class="col-xs-12 col-sm-10 col-md-8">
        <p>Name: {{member.name}}</p>
        <p>email: {{member.mail}}</p>
        <p>Membership Date: {{member.membershipDate | date:'dd/MM/yyyy'}}</p>
        <p>Membership Type: {{member.membershipType}}</p>
      </div>
    </div>
  </div>  
</div>
  1. For Membership Type radio button, options are added using ngFor which iterates over membershiptyes array defined in the Component class.
  2. For syncing up the form controls you will have to bind each form field with the form control created in the component. That is done by assigning formControlName to the name given in the component.

    formControlName="membershipType"

That's all for this topic Radio Button in Angular Form Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Checkbox in Angular Form Example
  2. FormGroup in Angular With Examples
  3. Angular Reactive Form Validation Example
  4. Angular Template-Driven Form Validation Example
  5. Service in Angular With Examples

You may also like-

  1. Setting Wild Card Route in Angular
  2. Angular Disable Button Example
  3. Angular Custom Property Binding Using @Input Decorator
  4. Angular Project Structure With File Description
  5. Best Practices For Exception Handling in Java
  6. List Comprehension in Python With Examples
  7. Var type in Java - Local Variable Type Inference
  8. Spring JdbcTemplate With ResultSetExtractor Example

No comments:

Post a Comment