स्ट्रक्चरल डायरेक्टिव्ज (ज्यांना * आहे, जसे *ngIf/*ngFor) DOM ला बदलतात. हे सिंटॅक्स साखर आहे — हुड अंतर्गत, Angular घटक मध्ये लपवतो आणि डायरेक्टिव्ह हे नियंत्रित करतो की ते टेम्पलेट कधी/कसे रेंडर केले जाते.
स्ट्रक्चरल डायरेक्टिव्ज (ज्यांना * आहे, जसे *ngIf/*ngFor) DOM ला बदलतात. हे सिंटॅक्स साखर आहे — हुड अंतर्गत, Angular घटक मध्ये लपवतो आणि डायरेक्टिव्ह हे नियंत्रित करतो की ते टेम्पलेट कधी/कसे रेंडर केले जाते.
*<ng-template><!-- what you write -->
<p *ngIf="isVisible">Hello</p>
<!-- what Angular actually does -->
<ng-template [ngIf]="isVisible">
<p>Hello</p>
</ng-template>
* Angular ला सांगते: "हा घटक टेम्पलेटमध्ये लपवा, आणि डायरेक्टिव्हला हे ठरवू द्या की त्याला DOM मध्ये कधी छाप करायचे." <ng-template> हा निष्क्रिय मार्कअप चंड आहे जो डायरेक्टिव्ह त्याला अमलात आणत नाही तोपर्यंत रेंडर होत नाही.
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>
इंजेक्ट केलेले दोन भाग महत्वाचे आहेत: TemplateRef हे घटकाचे टेम्पलेट आहे ("काय रेंडर करायचे"), आणि ViewContainerRef हे DOM मधील स्थान आहे ("कुठे"). डायरेक्टिव्ह घटक जोडण्यासाठी createEmbeddedView कॉल करतो किंवा काढण्यासाठी 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> }
हे नवीन सिंटॅक्स अधिक वाचनीय आणि कार्यक्षम आहे, जरी अंतर्निहित जोडणे/काढणे संकल्पना समान आहे.
* → <ng-template> desugaring समजून घेतल्याने असे समजते की *ngIf/*ngFor DOM कसे जोडतात आणि काढतात, आणि आपल्याला कस्टम स्ट्रक्चरल डायरेक्टिव्ज बनवण्यास अनुमती देते (TemplateRef + ViewContainerRef वापरून) उन्नत टेम्पलेट नियंत्रणासाठी — उदाहरणार्थ, परवानगी-आधारित रेंडरिंग, कस्टम रिपीटर्स, किंवा आळस छाप.
हे हे स्पष्ट करते की तुम्ही एका घटकावर दोन स्ट्रक्चरल डायरेक्टिव्ज (*ngIf आणि *ngFor) का ठेवू शकत नाही: प्रत्येकाला स्वतःचा टेम्पलेट रॅपर हवा आहे.