ਢਾਂਚਾਗਤ ਨਿਰਦੇਸ਼ (* ਦੇ ਨਾਲ, ਜਿਵੇਂ *ngIf/*ngFor) DOM ਨੂੰ ਬਦਲਦੇ ਹਨ। syntactic sugar ਹੈ — ਹੁੱਡ ਦੇ ਅੰਦਰ, Angular ਤੱਤ ਨੂੰ ਵਿੱਚ ਲਪੇਟਦਾ ਹੈ ਅਤੇ ਨਿਰਦੇਸ਼ ਇਹ ਨਿਯੰਤ੍ਰਿਤ ਕਰਦਾ ਹੈ ਕਿ ਉਹ ਟੇਮਪਲੇਟ ਕਦਾ/ਕਿਵੇਂ ਰੈਂਡਰ ਹੋਵੇ।
ਢਾਂਚਾਗਤ ਨਿਰਦੇਸ਼ (* ਦੇ ਨਾਲ, ਜਿਵੇਂ *ngIf/*ngFor) DOM ਨੂੰ ਬਦਲਦੇ ਹਨ। syntactic sugar ਹੈ — ਹੁੱਡ ਦੇ ਅੰਦਰ, 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 ਵਿੱਚ stamp ਹੋਵੇ।" <ng-template> markup ਦਾ ਇੱਕ ਬੇ-ਜਾਣ ਹੋਇਆ ਹਿੱਸਾ ਹੈ ਜੋ ਉਦੋਂ ਤੱਕ ਰੈਂਡਰ ਨਹੀਂ ਹੋਇਆ ਜਦੋਂ ਤੱਕ ਕਿ ਇੱਕ ਨਿਰਦੇਸ਼ ਇਸਨੂੰ ਤਤਕਾਲ ਨਹੀਂ ਕਰਦਾ।
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 ਭਾਗ ਮੁੱਖ ਹਨ: 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> }
ਇਹ ਨਵਾਂ syntax ਵਧੇਰੇ ਪੜ੍ਹਨਯੋਗ ਅਤੇ ਵਧੇਰੇ ਕੁਸ਼ਲ ਹੈ, ਹਾਲਾਂਕਿ ਸਮਰਥਨ ਜੋੜਨ/ਹਟਾਉਣ ਦੇ ਸੰਕਲਪ ਬਰਾਬਰ ਹਨ।
* → <ng-template> desugaring ਨੂੰ ਸਮਝਣਾ ਇਸ ਨੂੰ ਸਪੱਸ਼ਟ ਕਰਦਾ ਹੈ ਕਿ *ngIf/*ngFor DOM ਨੂੰ ਕਿਵੇਂ ਜੋੜਦਾ ਅਤੇ ਹਟਾਦਾ ਹੈ, ਅਤੇ ਤੁਹਾਨੂੰ ਕਸਟਮ ਢਾਂਚਾਗਤ ਨਿਰਦੇਸ਼ (TemplateRef + ViewContainerRef ਦੀ ਵਰਤੋਂ ਕਰਕੇ) ਬਣਾਉਣ ਦੀ ਆਗਿਆ ਦਿੰਦਾ ਹੈ ਉੱਨਤ ਟੇਮਪਲੇਟ ਕੰਟਰੋਲ ਲਈ — ਉਦਾਹਰਣ ਲਈ ਅਨੁਮਤੀ-ਆਧਾਰਿਤ ਰੈਂਡਰਿੰਗ, ਕਸਟਮ repeaters, ਜਾਂ ਆਲਸ stamping।
ਇਹ ਇਹ ਵੀ ਸਪੱਸ਼ਟ ਕਰਦਾ ਹੈ ਕਿ ਤੁਸੀਂ ਇੱਕ ਤੱਤ ਉੱਤੇ ਦੋ ਢਾਂਚਾਗਤ ਨਿਰਦੇਸ਼ (*ngIf ਅਤੇ *ngFor) ਕਿਉਂ ਨਹੀਂ ਲਗਾ ਸਕਦੇ: ਹਰੇਕ ਨੂੰ ਆਪਣਾ ਰਾਪਰ ਚਾਹੀਦਾ ਹੈ।