Conditioning the logic and Toggle button

The angular, we can control tag element with help of if condition. In this example, we will control div element through if condition and toggle.

  1. We will display the div element content on a page only when if the condition showMore variable is true.
  2. We can display the div element content through toggle button

 

Add the following line of app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <h3>Hello everyone !</h3>
  <h3>My name is {{ emp.fname }} {{ emp.lname }}</h3>
  <button (click)="moreInfo()">More Details</button>
  <div *ngIf="showMore === true">
    <h3>I live in {{ emp.city}}</h3>
  </div>
  <button (click)="showDiv = !showDiv">Toggle Me</button>
  <div *ngIf="showDiv" style="color:white; background-color:blue; width:25%">Content 1</div>
  <div *ngIf="showDiv" style="color:white; background-color:red; width:25%">Content 2</div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public emp = {fname: 'Happy', lname: 'Singh', city: 'Delhi'};

  public showMore = false;

  moreInfo(){
    this.showMore = true;
  }

}