Thursday, June 21, 2018

$implicit in Angular!

At an Angular 4 application if the context for a variable has an $implicit at it's root at the TypeScript side of a component, this may be used as a default setting for a token let- variable at a template tag in a component's template. So, for example, something like so:

this.cat = { isCalico: false, numberOfLives: 9 };

 
 

...in the TypeScript for a component may be used at the component's template like so:

<ng-container *ngTemplateOutlet="kittyTemplate;context: cat"></ng-container>

 
 

Now imagine that kittyTemplate looks like so:

<ng-template #kittyTemplate let-feline>
   <h1>Felis catus</h1>
   <div>
      Calico? {{ feline.isCalico ? 'Yes' : 'No' }}
   </div>
   <div>
      Mana: {{ feline.numberOfLives }}
   </div>
</ng-template>

 
 

Alright, what is above is legit and will work. This suggests that you may think of this trick, the $implicit trick, like so:

<ng-template #kittyTemplate let-feline="$implicit">
   <h1>Felis catus</h1>
   <div>
      Calico? {{ feline.isCalico ? 'Yes' : 'No' }}
   </div>
   <div>
      Mana: {{ feline.numberOfLives }}
   </div>
</ng-template>

No comments:

Post a Comment