I am sharing a simple example here in this post showing how to toggle or show and hide elements in Angular 4. Let us assume I have a <div> element, which has few other elements like textbox and buttons. I wish to show and hide the elements with the click of a button.
In my example here, I am using the *ngIf directive in Angular 4 to toggle or show and hide elements. The Angular 4 ngIf will add or remove an elements from the DOM, based on a condition such as true or false.
Here’s how I do it. I have a button control in my application’s template along with a <div> element that has few other elements like textbox and labels. Its like a form. All I want is to show the elements whenever necessary and hide when not required.
The Template
<button (click)="toggle()" id="bt"> {{buttonName}} </button> <ng-container *ngIf="show"> <div style="margin: 0 auto;text-align: left;"> <div> <label>Name:</label> <div><input id="tbname" name="yourname" /></div> </div> <div> <label>Email Address:</label> <div><input name="email" id="email" /></div></div> <div> <label>Additional Information (optional):</label> <div><textarea rows="5" cols="46"></textarea></div> </div> </div> </ng-container>
The Application Component
Open the app.components.ts file, copy the code and paste it in the file.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { public show:boolean = false; public buttonName:any = 'Show'; ngOnInit () { } toggle() { this.show = !this.show; // CHANGE THE NAME OF THE BUTTON. if(this.show) this.buttonName = "Hide"; else this.buttonName = "Show"; } }
No comments:
Post a Comment