How to Show Hide or Toggle Elements in Angular 5 and 4?
Result looks like –
In this post, I am sharing a sample code for demo
“how to toggle or show and hide elements in Angular 5 and 4”. In the current scenario,
I have a HTML <div> element,
which contains some HTML elements like textbox,
password and buttons. It will show and hide the dive – form elements after click
on button.
Let’s see in the below example -
Component.html
-
<!-- Show Hide or Toggle Elements in Angular 5 and 4 -->
<button (click)="toggle()" id="btToggle" class="btn btn-info
btn-lg" >{{button_name}}</button>
<div *ngIf="show_dialog">
<div style="padding-left: 50px;">
<div>
<div>Email - <input id="email" type="text" name="txtEmail" /></div>
</div>
<div>
<div>Password - <input id="txtPasword" type="password" name="password" /></div>
</div>
<div>
<label>About you
(optional)-</label>
<div><textarea rows="4" cols="50"></textarea></div>
</div>
<div>
<div><button id="btAddLogin" class="btn btn-info
btn-lg" >Add</button>
</div>
</div>
</div>
</div>
Component.ts
–
import { Component, OnInit } from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
import { stringify } from '@angular/core/src/render3/util';
import { variable } from '@angular/compiler/src/output/output_ast';
import { trigger,state, group, style,transition,animate,keyframes,query,stagger } from '@angular/animations';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css'],
animations: [ ]
})
export class UserComponent implements OnInit {
date; //date Variable
logedInForm; //These are
variables
emailId;
password;
public show_dialog : boolean = false;
public button_name : any = 'Show Login Form!';
constructor() { }
ngOnInit() {
this.date = new Date(); // Today date and time
//Login Validation
this.logedInForm = new FormGroup({
emailId: new FormControl("youremail@gmail.com",
Validators.compose([
Validators.required,
Validators.pattern("[^ @]*@[^
@]*")
])),
password: new FormControl('YourPassword', [
Validators.minLength(8),
Validators.required])
});
}
toggle() {
this.show_dialog = !this.show_dialog;
// CHANGE THE TEXT OF THE BUTTON.
if(this.show_dialog)
this.button_name = "Hide Login
Form!";
else
this.button_name = "Show Login
Form!";
}
}
Result looks like –