संरचनात्मक निदेश (वे जो * के साथ हैं, जैसे *ngIf/) DOM को बदलते हैं। syntactic sugar है — पर्दे के पीछे, Angular element को में लपेटता है और निदेश नियंत्रित करता है कि यह template कब/कैसे render होता है।
संरचनात्मक निदेश (वे जो * के साथ हैं, जैसे *ngIf/) DOM को बदलते हैं। syntactic sugar है — पर्दे के पीछे, Angular element को में लपेटता है और निदेश नियंत्रित करता है कि यह template कब/कैसे render होता है।
*ngFor*<ng-template><!-- what you write -->
<p *ngIf="isVisible">Hello</p>
<!-- what Angular actually does -->
<ng-template [ngIf]="isVisible">
<p>Hello</p>
</ng-template>
* Angular को कहता है: "इस element को template में लपेटो, और निदेश को decide करने दो कि इसे DOM में कब stamp करना है।" <ng-template> एक inert markup का टुकड़ा है जो तब तक render नहीं होता जब तक कोई निदेश इसे instantiate न कर दे।
import { Directive, Input, TemplateRef, ViewContainerRef } from "@angular/core";
@Directive({ selector: "[appUnless]" }) // *appUnless = "the opposite of ngIf"
export class UnlessDirective {
constructor(
private templateRef: TemplateRef<any>, // the wrapped <ng-template>
private viewContainer: ViewContainerRef, // where to render it
) {}
@Input() set appUnless(condition: boolean) {
if (!condition) {
this.viewContainer.createEmbeddedView(this.templateRef); // render it
} else {
this.viewContainer.clear(); // remove it
}
}
}
// usage: <p *appUnless="isHidden">Shown when isHidden is false</p>
दोनों injected pieces महत्वपूर्ण हैं: TemplateRef element का template है ("क्या render करना है"), और ViewContainerRef DOM में स्थान है ("कहां")। निदेश createEmbeddedView को call करता है element add करने के लिए या clear को हटाने के लिए।
<!-- newer Angular replaces *ngIf/*ngFor with built-in block syntax -->
@if (isVisible) { <p>Hello</p> } @else { <p>Hidden</p> }
@for (item of items; track item.id) { <li>{{ item.name }}</li> }
यह नया syntax अधिक readable और performant है, हालांकि अंतर्निहित add/remove अवधारणा समान है।
* → <ng-template> desugaring को समझने से यह स्पष्ट हो जाता है कि *ngIf/*ngFor कैसे DOM add और remove करते हैं, और यह आपको custom structural directives बनाने की अनुमति देता है (TemplateRef + ViewContainerRef का उपयोग करके) advanced template control के लिए — जैसे permission-based rendering, custom repeaters, या lazy stamping।
यह यह भी स्पष्ट करता है कि आप एक ही element पर दो structural directives (*ngIf और *ngFor) क्यों नहीं रख सकते: प्रत्येक को अपना template wrapper चाहिए।