Greetings everyone, I am diving into Angular 2 and attempting to create a basic Todo application. Unfortunately, I've hit a roadblock. My array interpolation seems to be malfunctioning. Any assistance would be greatly appreciated.
Here is my AppComponent code:
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 todoItem: Todo = new Todo();
todoItem.titile = this.title;
this.todos.push(todoItem);
}
addToDo(title: string) {
let todoItem: Todo = new Todo();
todoItem.titile = title;
this.todos.push(this.todoDataService.addTodo(todoItem));
console.log(this.todos);
}
ngOnInit() {
this.todos = [];
}
}
This is how my AppModule looks like:
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 { }
The structure of my Todo class:
export class Todo {
id: number;
titile: string = '';
complete: boolean;
constructor(values: Object = {}) {
Object.assign(this, values);
}
}
My implementation of TodoDataService:
import { Injectable } from '@angular/core';
import { Todo } from './todo';
@Injectable()
export class TodoDataService {
lastId: number = 0;
constructor() { }
addTodo(todo: Todo): Todo {
console.log(todo);
if (!todo.id)
todo.id = ++this.lastId;
return todo;
}
}
And finally, the HTML file:
<div style="text-align:center">
<input type="text" (keyup.enter)="addToDo(inputText.value)" #inputText>
</div>
<div>
<p>{{ todos }}</p>
</div>
I have tried various approaches but it seems that the data is not being displayed correctly. Additionally, I want to show all the array data only if its size is greater than 0, but that functionality is also not working as expected. Any suggestions or insights would be highly valued. Thank you in advance!