简体   繁体   中英

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 ". 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. 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. that is why you are getting error.

you can declare variable in angular by using "let" keyword. ex : let variableName = index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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