大家好我是Angular 2的新手,嘗試構建示例Todo應用程序,但我被卡在中間。我的數組插值不起作用。請幫忙。Angular 2 Interpolation for array not working
這是我的AppComponent。
import { Component,OnInit } from '@angular/core';
import { Todo } from './todo';
import { TodoDataService } from './todo-data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers:[TodoDataService],
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app';
todos:Todo[];
constructor(private todoDataService : TodoDataService){
this.todos=[];
let todon:Todo=new Todo();
todon.titile=this.title;
this.todos.push(todon);
}
addToDo(title:string){
let todon:Todo=new Todo();
todon.titile=title;
this.todos.push(this.todoDataService.addTodo(todon));
console.log(this.todos);
}
ngOnInit() {
this.todos=[];
}
}
我的AppModule如下:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { TodoDataService } from './todo-data.service';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [TodoDataService],
bootstrap: [AppComponent]
})
export class AppModule { }
我的Todo類:
export class Todo {
id:number;
titile:string='';
complete:boolean;
constructor(values:Object={}){
Object.assign(this,values);
}
}
我TodoDataService類
import { Injectable } from '@angular/core';
import { Todo } from './todo';
// Here i am just incrementing lastid and returing new todo object each time
@Injectable()
export class TodoDataService {
lastId:number =0;
constructor() { }
addTodo(todo:Todo):Todo{
console.log(todo);
if(!todo.id)
todo.id = ++this.lastId;
return todo;
}
}
最後的html文件
<!--My input text field and ngIf and ngFor directives-->
<div style="text-align:center">
<input type="text" (keyup.enter)="addToDo(inputtext.value)" #inputtext>
<!-- <div *ngIf="todos.legnth > 0">
<ul>
<li *ngFor="let todo of todos">
<label>{{todo.title}}</label>
</li>
</ul>
</div> -->
</div>
<div>
<p>{{ todos }}</p>
</div>
正如你在上面看到的,我嘗試了所有的東西,但沒有顯示出來。另外我想顯示所有數組數據只有當我的數組大小大於0.那也不工作。請提供您寶貴的意見和建議。
你也有兩個錯別字 - 你的Todo類設置「titile」,而是嘗試在視圖中顯示「.title僞」。你也有todos.legnth而不是todos.length – glendaviesnz
是的,這是錯誤的感謝幫助。從我這邊來看是愚蠢的錯誤。 –