Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Directive *ngIf ====== We can use ngIf directive to control an UI element to show or not. The syntax is: <code><DOM_ELEMENT *ngIf="condition_expression"> ...THE CONTENT... </DOM_ELEMENT></code> ''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. ===== Example ===== 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. {{ :ng:ng_ngif.png?nolink&400 |}} Assume our component name is ''servers''. ==== servers.component.html ==== 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''. <code> <p *ngIf="bIsClicked">The button is clicked</p> <button (click)="onButtonClicked()">Click Me!</button> </code> ==== servers.component.ts ==== 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. <code> import { Component, OnInit } from '@angular/core'; @Component({ 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; } } </code> ng/directive_ngif.txt Last modified: 2019/11/18 16:00by chongtin