Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

Angular template loading if

I want to make a component that either shows a loading spinner or the content. It's template looks like this

<ng-template  [ngIf]="loader.isLoading">
  <div class="loader">
    <div><span class="fas fa-circle-notch fa-spin fa-4x"></span></div>
    <ul>
      <li *ngFor="let m of loader.messages">{{m}}</li>
    </ul>
  </div>
</ng-template>

<ng-template [ngIf]="!loader.isLoading">
  <ng-content></ng-content>
</ng-template>

and its called like this

<loader [loader]="loader">
  Now we have loaded: {{ theThingThatWasLoading }}.
</loader>

However, the <ng-content> template is rendered in all cases. Why is the ngIf being ignored? Is there a workaround?

question from:https://stackoverflow.com/questions/65936892/angular-template-loading-if

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/

ng-template tag we are simply defining a template

The syntax you're looking for is:

<div class="loader" *ngIf="loader.isLoading; else content">
   <div><span class="fas fa-circle-notch fa-spin fa-4x"></span></div>
   <ul>
     <li *ngFor="let m of loader.messages">{{m}}</li>
   </ul>
</div>

<ng-template #content>
  <ng-content></ng-content>
</ng-template>

This is also practical if you would want to show the loader on several locations within the same component template. Otherwise, you can use <ng-container *ngIf="condition"> for "cleaner" syntax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...