数组不工作的Angular 2插值

时间:2017-07-02 05:05:14

标签: angular typescript

嗨所有我是Angular 2的新手,并尝试构建示例Todo应用程序,但我陷入了中间。我对数组的插值不起作用。请帮忙。

这是我的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时显示所有数组数据。这也无法正常工作。请提供宝贵的意见和建议。

2 个答案:

答案 0 :(得分:3)

因为

<!-- <div *ngIf="todos.legnth > 0">

在构造函数中,您只推送一个值

this.todos.push(todon);

如此长度1.再次在ngOnInit中,您将其清除为

this.todos = [];

所以长度再次为0。因此,您将无法看到数据。

即使您使用以下方法添加新Todos

addTodo(todo:Todo):Todo{

你没有把todo推到this.todos阵列。

答案 1 :(得分:3)

首先,您必须取消注释块

<!-- <div *ngIf="todos.legnth > 0">
<ul>
<li *ngFor="let todo of todos">
<label>{{todo.title}}</label>
</li>
</ul>
</div> -->

并更正待办事项的语法。长度:它不是 legnth