angular - What is ng-template and why do I bind *ngIf then else to it? -
when use *ngif and/or else statement, why have bind template variable attached ng-template element? example:
this works:
<div *ngif="show; else elseblock">text show</div> <ng-template #elseblock>alternate text while primary text hidden</ng-template> but not work:
<div *ngif="show; else elseblock">text show</div> <div #elseblock>alternate text while primary text hidden</div> i noticed adding class not work either:
<ng-template #elseblock class="my-class">   alternate text while primary text hidden </ng-template> what's special ng-template? how different?
this because structural directives in angular create embedded views. embedded view created using both templateref , viewcontainerref. can read more them in exploring angular dom manipulation techniques using viewcontainerref.
an embedded view similar host views created components. view contains nodes see in component template or inside ng-template tag. embedded view component template without component class. here few examples of how structural directives create embedded views.
ngif
  private _updateview() {     if (this._context.$implicit) {       ...         if (this._thentemplateref) {           this._thenviewref =               // here embedded view created               this._viewcontainer.createembeddedview(this._thentemplateref, this._context);         }       }     } else {       if (!this._elseviewref) {        ...           this._elseviewref =               // here embedded view created               this._viewcontainer.createembeddedview(this._elsetemplateref, this._context);         }       }     }   } ngfor
  private _applychanges(changes: iterablechanges<t>) {     const inserttuples: recordviewtuple<t>[] = [];     changes.foreachoperation(         (item: iterablechangerecord<any>, adjustedpreviousindex: number, currentindex: number) => {           if (item.previousindex == null) {             // here embedded view created             const view = this._viewcontainer.createembeddedview(                 this._template, new ngforofcontext<t>(null !, this.ngforof, -1, -1), currentindex); 
Comments
Post a Comment