Sarang Shinde Sarang Shinde - 5 months ago 31
TypeScript Question

Angular 2 Interpolation for array not working

Hi All i am new to Angular 2 and trying to build sample Todo app but i am stuck in middle. My interpolation for array is not working. Please help.

This is my 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=[];

}
}


My AppModule is as follows:

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 { }


My Todo class:

export class Todo {

id:number;
titile:string='';
complete:boolean;

constructor(values:Object={}){
Object.assign(this,values);
}
}

My TodoDataService class
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;
}

}


Finally html file

<!--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>


As you can see above i tried all things but it is not getting displayed. Also i want to display all array data only if my array size is greater than 0. That also not working. Please provide your valuable inputs and suggestions.

Answer Source

First, you must uncomment the block

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

And correct the syntax of todos.length : it is not legnth