Angular 2 First Item in Array Missing using *ngFor

拟墨画扇 提交于 2019-12-02 02:45:47

The issue is that you are Bootstrapping TeacherComponent in your app.module and it being treated as an entry component which makes the first render break for our purposes.

This change will make it render properly:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import { TeacherComponent } from './teacher.component';

@NgModule({
  imports: [ BrowserModule ],
  declarations: [TeacherComponent, AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

And here's some reading on what to bootstrap https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-bootstrap_vs_entry_component

I don't see any issue, I tried this in this Plunker! and it works.

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

@Component({
  selector: 'my-app',
  template: `<h3>Angular 2 First Item in Array Missing using *ngFor</h3>
     <pre>{{teachers | json}}</pre>
    <teacher *ngFor="let t of teachers; let i = index" [teacherName]="t" [index]="i"></teacher>
  `
})
export class AppComponent {
   public teachers: string[] = [
        "Erty",
        "Dave",
        "Sarah",
        "Walter"
    ];
}

@Component({
    selector: 'teacher',
    template: `
        <p>Teacher {{index}}: {{teacherName}}</p>
    `
})
export class TeacherComponent {
    @Input() teacherName: string;
    @Input() index: number;

    ngOnInit() {
        console.log(this.teacherName);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!