I am new to angular and trying to create a simple todo app.
I used [(ngModel)] to pass the input value to the component but it seems i am doing it in incorrect way.
This is my code
HTML:
<div class="todo-app">
<h1>Todo List</h1>
<div>
<input type="text" class="input" placeholder="Enter your task" autofocus="" [(ngModel)]="value">
<button class="btn" (click)="addTodo()">Add</button>
</div>
</div>
ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.styl']
})
export class AppComponent {
todos = [];
id:number = 0;
addTodo() {
this.todos = [...this.todos, {title: this.value, id: this.id++, completed: false}];
return this.todos;
}
removeTodo(id:number) {
return this.todos.filter(todo => todo.id !== id)
}
toggleCompletionState(id:number) {
this.todos.map(todo => todo.id === id ? {...todo, completed: !todo.completed} : todo)
}
getAllTodos() {
return this.todos;
}
}
What is wrong here and why ngModel doesn't work??
On your template since you had assign value on your ngModel, declare it also on your Component to be able to access its instance there.
HTML
<input type="text"
class="input"
placeholder="Enter your task"
[(ngModel)]="value"> // this 'value' must be instantiated on your component
Component
@Component({...}) {
value: string; // Add this as you had used and assign it to your ngModel
addTodo() {
console.log(this.value); // this will now have a value depends on your input from ngModel
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With