Sunday, April 8, 2018

How do I hand a template and data into an Angular 5 component separately and then get the template to play nicely with the data?

I found a way. I made the default new application with the Angular CLI. In the token template, app.component.html, I added the following at the very bottom:

<new-stuff [dataPoints]="['foo','bar','baz','qux']">
   <ng-template #templateReference let-handIn>
      <strong><em>{{handIn}}</em></strong>
   </ng-template>
</new-stuff>

 
 

Alright, for this to work, we need a new component to hand stuff into. I made such a component and just called it NewComponent and it looks like this:

import { Component, ContentChild, TemplateRef, Input } from '@angular/core';
@Component({
   selector: 'new-stuff',
   templateUrl: './new.component.html'
})
export class NewComponent {
   @Input('dataPoints') data: Array<string>;
   @ContentChild('templateReference', {read: TemplateRef}) templateInstance:
         ContentChild;
}

 
 

We should loop NewComponent in at our module. Finally, the template for NewComponent looks like what follows. Note that we don't explicitly need the ng-content tag here as we are just handing in a template as content and if it does not explicitly get spat up in the markup of the component it will still behave as a template and tie into the ContentChild variable.

Look at this:
<ol>
   <li *ngFor="let datum of data">
      <ng-container *ngTemplateOutlet="templateInstance; context: {$implicit: datum}">
            </ng-container>
   </li>
</ol>
<ng-content></ng-content>

 
 

If we want to get away from the $implicit binding we could put this at the footer of app.component.html.

<new-stuff [dataPoints]="['foo','bar','baz','qux']">
   <ng-template #templateReference let-handIn="communicatedValue">
      <strong><em>{{handIn}}</em></strong>
   </ng-template>
</new-stuff>

 
 

NewComponent's template would thus change like so to accommodate at much.

Look at this:
<ol>
   <li *ngFor="let datum of data">
      <ng-container *ngTemplateOutlet="templateInstance; context: {communicatedValue:
            datum}"></ng-container>
   </li>
</ol>
<ng-content></ng-content>

No comments:

Post a Comment