Directive *ngIf

We can use ngIf directive to control an UI element to show or not. The syntax is:

<DOM_ELEMENT *ngIf="condition_expression"> ...THE CONTENT... </DOM_ELEMENT>

DOM_ELEMENT can be like <div>, <p>, or anything HTML tag. The condition_expression could be a Boolean variable or a function that return Boolean result.

In this example, we will let user to click a button. And if he clicked it, we will should “The button is clicked” on the top of it. Assume our component name is servers.


Here we user the Boolean variable bIsClicked to check should the first <p>…</p> be shown. A method onButtonClicked() within the component core code will be called to change the value of bIsClicked.

<p *ngIf="bIsClicked">The button is clicked</p>
<button (click)="onButtonClicked()">Click Me!</button>


Notice we have create a Boolean variable bIsClicked as boolean, and a function onButtonClicked(){…}. On the component init, we set the boolean to false, and if the function onButtonClicked() is called, we set the boolean to true.

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

  selector: 'app-servers',
  templateUrl: './servers.component.html',
  styleUrls: ['./servers.component.css']
export class ServersComponent implements OnInit {
  bIsClicked: boolean;

  constructor() { }

  ngOnInit() {
    this.bIsClicked = false;

  onButtonClicked() {
    this.bIsClicked = true;
  • ng/directive_ngif.txt
  • Last modified: 2019/11/18 16:00
  • by chongtin