Angular - 2.22- Using ngIf to exit data conditionally
So far, in the sample application we have built, we have not used any built-in directive beyond components themselves. The first one we will introduce is ngIf. Suppose we only want to display "The server was created" once the user has clicked the button - not on the first render. That conditional output is exactly what ngIf is designed for.
The ngIf directive works like an if statement at template level. To trigger Angular's structural-directive parser we must prefix it with a star: *ngIf. The star tells Angular that the directive changes the DOM structure - the element is either added or removed. Without the star, the directive will not behave correctly. The syntax is simple: <p *ngIf="serverCreated">Server "{{ serverName }}" was created</p>.
Wire the boolean in the class
- Declare a property
serverCreated = falsein the component class. - In the click handler that creates the server, set
this.serverCreated = true. - The expression inside the quotes can be any TypeScript expression returning a boolean: a property, a method call, a comparison, etc.
Now reload the application. At first glance the paragraph is absent. Type a name like "testserver 2" and click the button. The paragraph appears with the server name. If we open the browser DevTools and inspect the DOM before clicking, the paragraph is genuinely absent - Angular only leaves a small comment node as a placeholder where the directive lives. After the click, the paragraph is inserted at the correct position in the DOM.
This behaviour is fundamental: ngIf physically adds or removes the element from the DOM. It does not hide it with CSS, which would be a different mechanism. The leading star is the syntactic marker that designates a structural directive - the same star you will see on *ngFor. From here we can refine our conditional logic with else blocks, which we will introduce in the next lesson.