Direktif struktural (sing ana *, kaya *ngIf/) ngubah DOM kanthi . iku syntactic sugar — ing nduwur ngarep, Angular ngebungkus unsur kasebut ing lan direktif ngontrol apa/kepiye template kasebut dirender.
Direktif struktural (sing ana *, kaya *ngIf/) ngubah DOM kanthi . iku syntactic sugar — ing nduwur ngarep, Angular ngebungkus unsur kasebut ing lan direktif ngontrol apa/kepiye template kasebut dirender.
*ngFor*<ng-template><!-- what you write -->
<p *ngIf="isVisible">Hello</p>
<!-- what Angular actually does -->
<ng-template [ngIf]="isVisible">
<p>Hello</p>
</ng-template>
* ngandhani Angular: "bungkus unsur iki ing template, lan biarke direktif mutusake kapan dikirim menyang DOM." <ng-template> iku potongan markup sing ora aktif sing ora dirender nganti direktif nginstansiasi.
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>
Rong potongan sing disuntik iki kunci: TemplateRef iku template unsur ("apa sing dirender"), lan ViewContainerRef iku lokasi ing DOM ("nang endi"). Direktif ngruwat createEmbeddedView kanggo nambah unsur utawa clear kanggo nyilib.
<!-- 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> }
Syntaks sing luwih anyar iki luwih mudah dibaca lan efisien, sanajan konsep nambah/nyilib kasebut padha.
Pahaman tentang desugaring * → <ng-template> ndeskripsikan carane *ngIf/*ngFor nambah lan nyilib DOM, lan ngidini sampeyan mbangun direktif struktural khusus (nggunakake TemplateRef + ViewContainerRef) kanggo kontrol template canggih — contone, rendering adhedhasar ijin, pengulang khusus, utawa cap malas.
Iku uga klarifikasi mengapa sampeyan ora bisa nglebokake rong direktif struktural (*ngIf lan *ngFor) ing saiji unsur: saben siji kudu nggoleki wrapper template dhewe.