Solved this with the following:
Component template usage:
<search-field>
<ng-template let-item>
<span><strong>{{item.username}}</strong></span>
<span>{{item.email}}</span>
</ng-template>
</search-field>
Component template definition:
<div class="search-container">
<div class="search-input">
<input type="text" class="form-control" placeholder="Search users..." [(ngModel)]="searchString" (ngModelChange)="searchStringChanged($event)">
<div class="md-icon">search</div>
</div>
<ul class="search-results" *ngIf="searchResults.length > 0">
<li class="search-results__item" *ngFor="let item of searchResults">
<ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: item}"></ng-template>
</li>
</ul>
</div>
Component class:
@Component({...})
export class SearchFieldComponent {
@ContentChild(TemplateRef) templateRef: TemplateRef<any>;
// ...
}
The explanation:
Using ng-template
, I can use the let-item
syntax, where item
is the data that will be passed into the template on each iteration of the loop.
And in order to make the above possible, in the search-field
component I use ng-template
with ngTemplateOutlet
as the template reference, and ngTemplateOutletContext
is given the value {$implicit: item}
, where item
is the data I want to pass into the template.
Lastly, in the component class I need to use ContentChild
to get the reference to the template to use in the ngTemplateOutlet
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…