Jeremy Schultz
Jeremy Schultz

Reputation: 677

How to make template context for data in Angular 11

I have code like this in my component template in Angular 11:

<div class="volunteer" *ngFor="let volunteer of volunteers">
    <div class="personal-data">
        <h2>{{volunteer.personalData.firstName}} {{volunteer.personalData.lastName}}</h2>
        <p>{{volunteer.personalData.email}}</p>
        <p>{{volunteer.personalData.phone[volunteer.personalData.primaryPhone]}}</p>
    </div>
</div>

I'd like to put a data context around it so it knows to refer to the personalData object, something like this:

<div class="volunteer" *ngFor="let volunteer of volunteers">
    <div class="personal-data">
        {{#volunteer.personalData}}
            <h2>{{firstName}} {{lastName}}</h2>
            <p>{{email}}</p>
            <p>{{phone[primaryPhone]}}</p>
        {{/volunteer.personalData}}
    </div>
</div>

I'm not sure what the syntax is for this in Angular.

Upvotes: 0

Views: 1874

Answers (2)

Erik
Erik

Reputation: 867

You can use <ng-template> with a context variable. You can pass in an object at [ngTemplateOutletContext] and use it inside the template. Not sure about the primaryPhone part, but if you make it one of the properties of volunteer you should be good.

<div class="volunteer" *ngFor="let volunteer of volunteers">
    <ng-template [ngTemplateOutlet]="volunteerTemplate"
    [ngTemplateOutletContext]="{volunteerToPass: volunteer}">
    </ng-template>
</div>

<ng-template #volunteerTemplate let-volunteerInTemplate="volunteerToPass">
    <div class="personal-data">
        <h2>{{volunteerInTemplate.firstName}} {{volunteerInTemplate.lastName}}</h2>
        <p>{{volunteerInTemplate.email}}</p>
        <p>{{volunteerInTemplate.phone}}</p>
    </div>
</ng-template>

Upvotes: 2

Julius Dzidzevičius
Julius Dzidzevičius

Reputation: 11000

You could use a structular directive as *ngIf and assign it to a template variable. So it will be a bit shorter:

<div class="volunteer" *ngFor="let volunteer of volunteers">
    <div class="personal-data" *ngIf="volunteer?.personalData as personalData">
        <h2>{{personalData.firstName}} {{personalData.lastName}}</h2>
        <p>{{personalData.email}}</p>
        <p>{{personalData.phone[personalData.primaryPhone]}}</p>
    </div>
</div>

Upvotes: 2

Related Questions