简体   繁体   English

如何使用ngFor指令获取angular 5中的第一个元素?

[英]how to get first element in angular 5 using ngFor directive?

ngFor directive worked fine when I used to show all the colors from an array of colors but when I tried to check whether it is first element of the array or not then it shows an error "can't bind to ngForFirst since it is not .... blah blah blah ". ngFor指令在我过去用来显示颜色数组中的所有颜色时工作正常,但是当我尝试检查它是否是数组的第一个元素时,它显示错误“无法绑定到ngForFirst,因为它不是。” ... 等等等等等等 ”。 It shows almost a page full of error. 它几乎显示了一个充满错误的页面。 I'm very new to angular and the tutorial I'm going through the tutor doesn't get any error. 我对angular非常陌生,我正在通过辅导老师学习的教程没有任何错误。 Don't know why. 不知道为什么。 Help me 帮我

    import { Component, OnInit } from '@angular/core';

    @Component({
     selector: 'app-test',
     template: `
       <div *ngFor = "let color of colors; first as i">
           <h3> {{i}}  </h3>
       </div>` ,
     styles: []
    })

    export class TestComponent implements OnInit {
      public name = "Dipesh";
      public colors = ["Red", "Black", "Green"];
      constructor() { }

      ngOnInit() {
      }

      }

Try this 尝试这个

 <div *ngFor = "let color of colors; let first = first; let last = last">
               <h3> {{first}}  </h3>
               <h3> {{last}}  </h3>
 </div>

You can access to the first element like this: 您可以像这样访问第一个元素:

<div *ngFor="let color of colors; let first = first;"> ...

Note: 注意:

You have more functionallity available like: odd , even or last 您可以使用更多功能,例如: 奇数偶数末尾

Official documentation here 官方文件在这里

with using "as" you try to translate " first " into " i " type object. 使用“ as”,您尝试将“ first ”转换为“ i ”类型的对象。 that is why you are getting error. 这就是为什么您会出错。

you can declare variable in angular by using "let" keyword. 您可以使用“ let”关键字以角度声明变量。 ex : let variableName = index 例如:让variableName =索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM