Update on templates

As the template is a real HTML tag for the web component, Angular introduced a new ng-template tag for templates. Angular enabled us to use else in ngIf in templates, as follows:

<div *ngIf="isOld; then   content else new_content">placeholder</div>   
<ng-template   #content><h2>old content body.</h2></ng-template>   
<ng-template   #new_content><h2>body of new content.</h2></ng-template>   

Here, if isOld is true, the content of the old template will be displayed. Otherwise, the content of the new template will be displayed.

Next, let's discuss the as keyword added to the template syntax. It is introduced to simplify the syntax of let. It enables us to store the results in a template variable:

<ul>   
   <li *ngFor="let book of   books | slice:0:10 as topTenBooks; index as idx">   
      {{ topTenBooks.length - idx   }}: { book.name }}   
   </li>   
</ul>   

Here, we used the as keyword to store the result of slice in the topTenBooks variable and further referenced it in the li tag. Note that we also gave an alias name, i, to index, which is the short form of the let i = index syntax.

We can also use the as keyword and async together, as shown:

<ul>   
   <li *ngFor="let book of   books$ | async">   
      {{ book.name }}   
   </li>   
</ul>    
<h3>{{ ( books$ |   async)?.length }} books</h3>   

Here, we have made our books collection as Observable. So, we have iterated through the array of books returned from Observable. Note that we also display the number of books returned from the Observable. However, this leads to a performance overhead as the async pipe used will rerun if there are changes. Further improvement, as follows, avoids such performance overhead:

<div *ngIf="books$ | async as   books">   
   <ul>   
      <li *ngFor="let book of   books">   
         {{ book.name }}   
      </li>   
   </ul>   
<div>   
<h3>{{  books.length }}   books</h3>   

Here, we used the as keyword to store a piped value in a parent component. Note that we used async only once.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.111.85