What does the ngIf directive do?
The *ngIf directive in Angular is a structural directive that conditionally adds or removes an element from the DOM based on a boolean expression.
How it works:
- If the condition is true (
true), Angular inserts the element into the DOM. - If the condition is false (
false), the element is removed from the DOM completely. - Supports additional branching via
else.
Example:
html
<p *ngIf="isVisible">This text is shown only if isVisible = true</p>
<ng-template #elseBlock>
<p>Text when false</p>
</ng-template>
<p *ngIf="isVisible; else elseBlock">Conditional text</p>Conclusion:
*ngIfcontrols the presence of elements in the DOM, not just their visibility via CSS.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.