Q1. What is *ngIf directive?
*ngIf is a structural directive that conditionally includes a template based on a boolean expression. If the expression is truthy, Angular renders the element; if falsy, it removes the element from the DOM. Example:
Welcome back!
Q2. How does *ngIf work internally?
Angular translates *ngIf into an wrapper. The element is added or removed based on the condition. Unlike CSS display:none, *ngIf physically removes the element, so its state is lost. This is important for performance and to avoid memory leaks.
Q3. Can you use *ngIf with an else condition?
Yes, Angular provides a syntax for else using . Example:
Welcome
Please log in
You can also use then and else together.Q4. What is the difference between *ngIf and hidden attribute?
*ngIf removes the element from the DOM, while hidden attribute (or [hidden] binding) only toggles CSS display property. *ngIf is better for expensive components or when you want to free resources, while hidden is quicker for simple toggles but the element remains in the DOM.
Q5. Can you use *ngIf with async pipe?
Yes, *ngIf works well with the async pipe. Common pattern:
{{ user.name }}
This subscribes to the observable and creates a variable for the emitted value.