Angular 2 use a “template” for ng-content to use inside component loop

后端 未结 1 1816
迷失自我
迷失自我 2020-12-06 03:22

I am trying to create a component that will do some stuff and loop over a result set. I want to be able to provide a \"template\" for the items in the looped result set.

相关标签:
1条回答
  • 2020-12-06 03:39

    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.

    0 讨论(0)
提交回复
热议问题