How can I use *ngFor current object outside of the ngFor?
Asked Answered
M

2

7

The title might seem weird but what im talking about is basically what this link is doing.

Im look for a way to use the current iterated person in a <tr> outside of the *ngFor scope.

In the link he used ng-repeat-start and ng-repeat-end to include multiple tag withing the ng-repeat. How can i achieve the same behavior withing Angular2 using *ngFor?

Mckinnie answered 31/8, 2016 at 12:35 Comment(0)
M
9

I had to use the <template> tag, which made the iterated objected accessible within it.

<ng-template let-person ngFor [ngForOf]="people">
    <tr>
        <td>{{person.name}}</td>
        <td>{{person.gender}}</td>
    </tr>
    <div>
        <span>{{person.details}}</span>
    </div>
</ng-template>

Hope it'll help somebody

Mckinnie answered 31/8, 2016 at 17:52 Comment(1)
Could you provide a link to Angular documentation on why this works? The information I got on the use of the HTML 5 template tag: angular.io/docs/ts/latest/guide/…Reorganization
I
0

The * in *ngFor (and really any angular directive) is shorthand that tells angular to surround the element in an ng-template, which is just the angular implementation of . You can read about how that happens at https://angular.io/guide/structural-directives, but I'll reproduce the relevant example below.

If your code contains

<div *ngIf='object'>{{object.property}}</div>

as part of the render process, angular transposes that to

<ng-template [ngIf]='object'>
   <div>{{object.property}}</div>
</ng-template>
Isabelleisac answered 13/9, 2018 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.