我正在嘗試Angular 2,而且我正面臨一個我不明白的奇怪問題。Angular 2 ngFor第一次發生undefined
我做一個簡單的待辦事項列表,當我執行我的應用我有這樣的錯誤消息:
我不明白爲什麼迭代中第一次出現是不確定的。我的數組是硬編碼的,所以我不知道爲什麼會有這個問題。 下面是該應用程序的代碼:
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { TodoNavComponent } from './app.todo-nav';
import { TodoListComponent } from './app.todo-list';
import { TodoComponent } from './app.todo';
@NgModule({
imports: [ BrowserModule ],
declarations: [ TodoNavComponent, TodoListComponent, TodoComponent ],
bootstrap: [ TodoNavComponent, TodoListComponent, TodoComponent ]
})
export class AppModule { }
app.todo-list.ts
import { Component } from "@angular/core";
import { TodoService } from "./app.service";
@Component({
selector: "todo-list",
template: `
<div class="container">
<ul class="list-group">
<todo *ngFor="let todo of todos" [todo]="todo"></todo>
</ul>
</div>`,
providers: [TodoService]
})
export class TodoListComponent {
todos: any[] = [
{ name: "Do shopping", done: false },
{ name: "Get some gaz for my car", done: true },
{ name: "Download last season of Game of Thrones", done: false }
];
constructor(private service: TodoService) {
service.todoAdded$.subscribe(
todo => {
this.todos.push(todo);
}
);
service.todoRemoved$.subscribe(
todo => {
this.todos = this.todos.filter(
(value, index, array) => {
return todo.name !== value.name;
}
);
}
);
}
}
app.todo.ts
import { Component, OnDestroy, Input } from "@angular/core";
import { TodoService } from "./app.service";
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: "todo",
template: `
<li class="list-group-item">
<i class="pull-right glyphicon glyphicon-remove" (click)="remove()"></i>
{{todo.name}}
</li>`,
providers: [TodoService]
})
export class TodoComponent implements OnDestroy {
@Input() todo;
subscription: Subscription;
constructor(private service: TodoService){
this.subscription = service.todoAdded$.subscribe(
todo => {
this.todo = todo;
}
);
}
remove() {
this.service.removeTodo(this.todo);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
這裏是渲染:
我錯過了什麼? 我不明白爲什麼它只發生在第一次發生而不是其他發生。
謝謝!
此修復這個錯誤在這裏explaned:HTTP://計算器。com/questions/40291111/angular-2-first-item-in-array-missing-using-ngfor –