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

时间:2016-08-31 12:35:19

标签: javascript angular ngfor

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?

2 个答案:

答案 0 :(得分:8)

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

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

Hope it'll help somebody

答案 1 :(得分:0)

* ngFor中的*(实际上是任何angular指令)都是简写,它指示angular将其包围在ng-template中,这只是的有角实现。您可以在https://angular.io/guide/structural-directives上了解到这种情况,但我将在下面重现相关示例。

如果您的代码包含

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

作为渲染过程的一部分,角度将其转置为

<ng-template [ngIf]='object'>
   <div>{{object.property}}</div>
</ng-template>