【Angular Tips】Mat-Radio Buttons to Switching Different Forms

2018.09.07

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

*この記事は日本語と英語で書かれています。日本語版はこちら

In this mini Angular.js tutorial, we will use mat-radio button and ngIf conditions to switch around different forms.

Using radio buttons and ngIf statement doesn’t require jQuery which means you don’t have to deal with DOM add/remove classes anymore. (Amazing, isn't it?)

Outcome

stackblitz Demo

Angular Environment

My development environment looks like this.
Please install basic Angular modules if you have not installed yet.
I used Angular-cli v 6.1.5 in this tutorial.

$ ng -v

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 6.1.5
Node: 8.11.2
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.7.5
@angular-devkit/core         0.7.5
@angular-devkit/schematics   0.7.5
@angular/animations          6.1.4
@angular/cdk                 6.4.6
@angular/cli                 6.1.5
@angular/common              6.1.4
@angular/core                6.1.4
@angular/forms               6.1.4
@angular/material            6.4.6
@schematics/angular          0.7.5
@schematics/update           0.7.5
rxjs                         6.2.2
typescript                   2.9.2

Create a new project.

First of all, let's create a new project via Angular-cli.

ng new form-switcher

And go to the project directory you just created.

cd form-switcher

Let's make sure you have created new Angular project successfully by firing up the development server.

ng serve -o

You have successfully created a new project if you are seeing a page looks like below.
Press Ctrl + c to deactivate developer server whenever you want to.

angular-new-project

Then create a new component by typing: ng generate component form-switcher.

Now open app.component.html and delete all the auto-generated lines of code and replace to a line below.

<app-form-switcher></app-form-switcher>

By doing this, you can now see form-switcher.component.html content in a index page.

Let's check the index page again by typing ng serve -o. You now see the contents of app-form-switcher.html.

Add Modules to module.ts

Before we dive into coding, make sure to import modules in module.ts
Any components and modules you are using in the project, you must include in module.ts file

Three modules are required in this tutorial.
@angular/material
@angular/forms
@angular/platform-browser

Install those modules via npm and add them to module.ts.

`modal.component.ts`

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { FormSwitcherComponent } from './form-switcher/form-switcher.component';

// Reactive Form Module
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

// Radio Button
import {MatRadioModule} from '@angular/material';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';


@NgModule({
  declarations: [
    AppComponent,
    FormSwitcherComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    FormsModule,
    MatRadioModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Create Forms

Let’s create 3 forms to lead users to different search forms.

We will use form builder to generate reactive forms.

* In this tutorial I will not cover backend functionality. They will be explained in my next tutorial.

`form-switcher.component.ts`

import { Component, OnInit } from '@angular/core';
// Angular Reactive Form
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

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

  // Form
  public idSearchForm: FormGroup;
  public keywordSearchForm: FormGroup;
  public emailSearchForm: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.createForm ();
  }

  createForm () {
    this.idSearchForm = this.fb.group({
      someId: ['', Validators.required]
    });
    this.keywordSearchForm = this.fb.group({
      keyword: ['', Validators.required ]
    });
    this.emailSearchForm = this.fb.group({
      email: ['', Validators.email]
      });
  }
}

Then add forms to html page.

`form-switcher.component.html`

<html lang="ja">
  <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <title> Form Switcher Demo</title>
  </head>
  <body>
    <div class="SearchForm">
      <div id='idSearchForm'>
        <div class="center"><h2>ID Search</h2></div>
        <form [formGroup]="idSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">ID Search
            <input class="form-control" formControlName="someId" placeholder="enter some id here..">
          </label>
        </div>
  
        <button type="submit">
          Search
        </button>
        </form>
      </div><!--End of First Form-->

      <div id='keywordSearchForm'>
        <div class="center"><h2>Keyword Search</h2></div>
        <form [formGroup]="keywordSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">Keyword Search
            <input class="form-control" formControlName="keyword" placeholder="enter some keyword here..">
          </label>
        </div>
  
        <button type="submit">
          Search
        </button>
        </form>
      </div><!--End of Second Form-->

      <div id='emailSearchForm'>
        <div class="center"><h2>Email Search</h2></div>
        <form [formGroup]="emailSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">Email Search
            <input class="form-control" formControlName="email" placeholder="Enter email here..">
          </label>
        </div>
        <button type="submit">
          Search
        </button>
        </form>
      </div><!--End of Third Form-->

    </div><!--End of content-->

  </body>
</html>

Create Radio Buttons

Let’s add radio buttons.

Add two variables to form-switcher.component.ts

`form-switcher.component.ts`

  searchTypeSelected: string;
  searchTypes: string[] = ['ID', 'Keyword', 'Email'];

We will use ngFor to loop searchTypes array values to generate radio button options. When a option was chose, the value will be fetched in searchTypeSelectedvariable.

Then add radio buttons in form-switcher.component.html

`form-switcher.component.html`

      <mat-radio-group fxFlex fxFlexFill class="searchType-group" [(ngModel)]="searchTypeSelected">
        <mat-radio-button class="searchType" *ngFor="let ty of searchTypes" [value]="ty">
          {{ty}} <br />
        </mat-radio-button>
      </mat-radio-group>

Add ngIf Conditions to html form

Finally, let's add ngIf conditional statement to html

`form-switcher.component.html`

<html lang="ja">
  <body>
    <div class="SearchForm">
      <mat-radio-group fxFlex fxFlexFill class="searchType-group" [(ngModel)]="searchTypeSelected">
        <mat-radio-button class="searchType" *ngFor="let ty of searchTypes" [value]="ty">
          {{ty}} <br />
        </mat-radio-button>
      </mat-radio-group>
      <div id='idSearchForm' *ngIf="searchTypeSelected == 'ID'">
        <div class="center"><h2>ID Search</h2></div>
        <form [formGroup]="idSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">ID Search
            <input class="form-control" formControlName="someId" placeholder="enter some id here..">
          </label>
        </div>
  
        <button type="submit">
          送信
        </button>
        </form>
      </div><!--End of First Form-->

      <div id='keywordSearchForm' *ngIf="searchTypeSelected == 'Keyword'">
        <div class="center"><h2>Keyword Search</h2></div>
        <form [formGroup]="keywordSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">Keyword Search
            <input class="form-control" formControlName="keyword" placeholder="enter some keyword here..">
          </label>
        </div>
        <button type="submit">
          送信
        </button>
        </form>
      </div><!--End of Second Form-->

      <div id='emailSearchForm' *ngIf="searchTypeSelected == 'Email'">
        <div class="center"><h2>Email Search</h2></div>
        <form [formGroup]="emailSearchForm" class='form'>
        <div class="form-group">
          <label class="center-block">Email Search
            <input class="form-control" formControlName="email" placeholder="Enter email here..">
          </label>
        </div>
  
        <button type="submit">
          送信
        </button>
        </form>
      </div><!--End of Third Form-->

    </div><!--End of content-->

  </body>
</html>

Summary

Full source code is available at stackblitz.

Check more information at Angular Material website.

Angular Material
Angular Material Radio Button

Please feel free to leave a comment if you have any thoughts.