Throughout this Angular Show Hide on Radio Button click tutorial, you will learn how to show and hide div by clicking on the Radio Button in the Angular application using the ngModel directive.
This quick guide demonstrates DOM manipulation in angular; recently, I needed to hide and show div on radio button click.
To create such a feature, I followed a template-driven approach to create the radio buttons, bind the div to radio buttons, and hide and show after selecting.
If you haven’t installed the Angular CLI, execute the following command to install the Angular command-line interface.
npm install -g @angular/cli
This step is not required; however, if you have not created the angular app, then you may go ahead and execute the suggested command.
ng new ng-demo
Now, get inside the project directory.
cd ng-demo
Now, head over to main app module file and import the forms module in order to work with angular form. Append the suggested code in src/app/app.module.ts file.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Inside the angular HTML template, define the radio buttons, add the ngModel directive pass the value to it, similarly define the checked state and values.
Two divs were initially hidden and get into the visible state on radio button click.
Update the code in src/app/app.component.html file.
<div>
<h2>Angular Show/Hide Div on Radio Button Click</h2>
<label>
<input [value]="1" [(ngModel)]="sh" name="sh" type="radio" [checked]="isChecked" /> Adams
</label>
<label>
<input [value]="0" [(ngModel)]="sh" name="sh" type="radio" [checked]="!isChecked" /> Johnas
</label>
<div class="text-center purple" *ngIf="sh == 1">Adams</div>
<div class="text-center red" *ngIf="sh == 0">Johnas</div>
</div>
In the final step, you require to enter the given command on the command prompt and run the command to start the angular app server.
ng serve
Now, open the browser, type the given url to view the app.
http://localhost:4200
In this tutorial, we have explained how to hide and show HTML div on radio buttons click in angular application with the help of ngModel directive.
If you want to learn how to get the current route's name, component pathname or…
React show and hide example. In this tutorial, we will show you how to step…
Tabs are one of the best UI elements for displaying multiple contents in a single…
In this tutorial, we will learn how to create a toast notification component in the…
Bootstrap offers tons of custom UI solutions. On top of that, it is easy to…
React js counter using the useReducer hook example. In this post, we will learn how…