Angular 2 ngfor first,last,index loop

Pri*_*cee 59 angular-material angular

我试图将此示例中的第一个设置为默认值:plunkr

收到以下错误:

Unhandled Promise rejection: Template parse errors:
TypeError: Cannot read property 'toUpperCase' of undefined ("dButtonToggleGroup">
                                                            <md-button-toggle [ERROR ->]*ngFor="let indicador of indicadores; #first = first" value="indicador.id" [checked]="first">
      "): ng:///AppModule/HomeComponent.html@35:78
Parser Error: Unexpected token #, expected identifier, keyword, or string at column 31 in [let indicador of indicadores; #first = first] in ng:///AppModule/HomeComponent.html@35:78 ("       <md-button-toggle *ngFor="let indicador of indicadores; #first = first" value="indicador.id" [ERROR ->][checked]="first">
                                                                <span>{{ indicado"): ng:///AppModule/HomeComponent.html@35:153
Run Code Online (Sandbox Code Playgroud)

怎么了??

Ste*_*doo 120

看看这个plunkr.

绑定到变量时,需要使用括号.此外,当您想要获取html中元素的引用时,可以使用hashtag,而不是在模板中声明变量.

<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first"> 
...
Run Code Online (Sandbox Code Playgroud)

编辑: 感谢Christopher Moore:Angular暴露了以下局部变量:

  • index
  • first
  • last
  • even
  • odd

  • [`ngFor`]中的@Steveadoo(https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html)Angular暴露了以下局部变量`index`,`first`,` last`,`even`和`odd`.您能否更新答案以澄清未来用户的这一点? (20认同)
  • 您可以将“first as isFirst”(isFirst 是自定义变量)写入此处,而不是“let first = first”:https://angular.io/api/common/NgForOf#local-variables (4认同)

Seb*_*dez 38

以下是它在Angular 6中的完成情况

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>
</li>
Run Code Online (Sandbox Code Playgroud)

请注意从更改let first = firstfirst as isFirst

  • 这是ng6的正确方法 (2认同)

Roh*_*iya 7

通过这种方式,您可以*ngFor在 ANGULAR 中获得循环中的任何索引...

<ul>
  <li *ngFor="let object of myArray; let i = index; let first = first ;let last = last;">
    <div *ngIf="first">
       // write your code...
    </div>

    <div *ngIf="last">
       // write your code...
    </div>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我们可以使用这些别名 *ngFor

  • indexnumberlet i = index获取对象的所有指标。
  • firstbooleanlet first = first获取对象的第一个索引。
  • lastbooleanlet last = last获取对象的最后一个索引。
  • oddbooleanlet odd = odd获取对象的索引为奇数。
  • evenbooleanlet even = even获取对象的索引为偶数。