I am trying to understand Angular JS 2. When I try the code mentioned in https://angular.io/docs/js/latest/guide/user-input.html, I get a blank value inserted into the list after typing the text in input and hitting the enter key. Here is the ES5 I tried:
//ES5
function TodoList() {
this.todos = ["Eat Breakfast", "Walk Dog", "Breathe"];
this.addTodo = function(todo) {
this.todos.push(todo.value);
};
this.doneTyping = function($event) {
if($event.which === 13) {
this.addTodo($event.target.value);
$event.target.value = null;
}
}
}
TodoList.annotations = [
new angular.ComponentAnnotation({
selector: "todo-list"
}),
new angular.ViewAnnotation({
template:
'<ul>' +
'<li *ng-for="#todo of todos">' +
'{{ todo }}' +
'</li>' +
'</ul>' +
'<input #textbox (keyup)="doneTyping($event)">' +
'<button (click)="addTodo(textbox.value)">Add Todo</button>',
directives: [angular.NgFor]
})
];
document.addEventListener("DOMContentLoaded", function() {
angular.bootstrap(TodoList);
});
This exactly as mentioned in Angular.io/docs , has anyone else seen same issue? Is there an error in the documentation?
Figured out the issue, it is incorrect documentation in Angular JS 2. The code:
this.addTodo = function(todo) {
this.todos.push(todo.value);
};
should have been:
this.addTodo = function(todo) {
this.todos.push(todo);
};
as the value is passed to addTodo
from doneTyping
and also from button
.