Open In App

Show or hide children components in Angular 10

Prerequisites: Angular must be installed  

In this article, we will see how we can show or hide the child components in Angular.  



ng new myProject
ng serve -o  
ng generate component comp1  
<app-comp1></app-comp1>  
<button type="button" (click)="showhideUtility()">
    {{buttonTitle}}
</button>  




import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
   export class AppComponent {
   title = 'myProject';
   buttonTitle:string = "Hide";
   showhideUtility(){
   }
}




<div>
   This is the Child Component
</div>

div{
height:200px;
width: 200px;
border: 2px lightblue solid;
border-radius: 10px;
background-color: lightgreen;
}




import { Component } from '@angular/core';
@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'myProject';
 buttonTitle:string = "Hide";
 visible:boolean = true;
 showhideUtility(){
   this.visible = this.visible?false:true;
   this.buttonTitle = this.visible?"Hide":"Show";
 }
}




<app-comp1 *ngIf="visible"></app-comp1>      
<button type="button" (click)="showhideutility()">{{buttonTitle}}</button>

ng serve -o  

The project will run on http://localhost:4200 by default. You will the output like this:  

When Show button is Clicked

When Hide Button is Clicked




Article Tags :