Behind the scenes of *ngIf
Angular team implemented the *ngIf directive as a structural directive, which allows developers to conditionally include or exclude…
Behind the scenes of *ngIf
Angular team implemented the
*ngIfdirective as a structural directive, which allows developers to conditionally include or exclude elements in the DOM. Structural directives are a key part of Angular's template syntax and are responsible for changing the structure of the DOM by adding or removing elements.
How *ngIf Works
Frontend Usage
When you use *ngIf in an Angular template, it looks like this:
<div *ngIf="condition">
Content to show if the condition is true.
</div>
What Happens Behind the Scenes
Template Parsing:
- When Angular encounters the
*ngIfdirective in a template, it translates it into an<ng-template>element. The*syntax is syntactic sugar for an<ng-template>with anngIfdirective.
<ng-template [ngIf]="condition">
<div>
Content to show if the condition is true.
</div>
</ng-template>
**NgIf Directive**:
- The
NgIfdirective is implemented in Angular as a class with theDirectivedecorator. It listens for changes to the input condition and updates the DOM accordingly.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[ngIf]'
})
export class NgIf {
private hasView = false;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef
) {}
@Input() set ngIf(condition: boolean) {
if (condition && !this.hasView) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if (!condition && this.hasView) {
this.viewContainer.clear();
this.hasView = false;
}
}
}
Explanation of NgIf Implementation
Constructor:
- The
NgIfdirective injectsTemplateRefandViewContainerRef. TheTemplateRefis a reference to the template (the HTML within the*ngIf), and theViewContainerRefis a reference to the container that holds the view.
Input Property:
- The
ngIfproperty is an input to the directive. The@Input()decorator binds the property to the directive input, and thesetaccessor is used to react to changes in the input value.
Condition Handling:
- If the condition is
trueand the view is not yet created,createEmbeddedViewis called to instantiate the template and add it to the DOM. - If the condition is
falseand the view is created,clearis called to remove the view from the DOM.
메타데이터
- post_id
- eaf39b2ed30d
- slug
- behind-the-scenes-of-ngif-eaf39b2ed30d
- url
- https://medium.com/@manikantasai413.ms/behind-the-scenes-of-ngif-eaf39b2ed30d
- canonical_url
- https://medium.com/@manikantasai413.ms/behind-the-scenes-of-ngif-eaf39b2ed30d
- author_url
- https://medium.com/@manikantasai413.ms
- status
- ok
- fetched_at
- 2026-07-23 07:31:57