I am trying to implement Event Emitter such that when a todo is inserted into the db, it is added to the list of todos. But it does not work. Please find the code below: The todoinput component(todo.input.html): component which adds a todo to the database
import { Component, OnInit, EventEmitter, Output } from '@angular/core';
import { Todos } from '../../models/Todos';
import { TodosService } from '../../services/todos.service';
@Component({
selector: 'app-todoinput',
templateUrl: './todoinput.component.html',
styleUrls: ['./todoinput.component.css']
})
export class TodoinputComponent implements OnInit {
@Output() newTodo: EventEmitter<Todos> = new EventEmitter();
constructor(private _todosService: TodosService) { }
ngOnInit() {
}
addTodo(text) {
this._todosService.addTodo({
text: text,
}).subscribe((todo) => {
this.newTodo.emit(todo);
})
}
}
The app.component.html: which holds all the components.
<app-navbar></app-navbar>
<app-todoinput (newTodo)="onNewTodo($event)">
</app-todoinput>
<app-todolist>
</app-todolist>
The todolist.component.ts: which adds todo to the list of todos
import { Component, OnInit } from '@angular/core';
import { Todos } from '../../models/Todos';
import { TodosService } from '../../services/todos.service';
@Component({
selector: 'app-todolist',
templateUrl: './todolist.component.html',
styleUrls: ['./todolist.component.css']
})
export class TodolistComponent implements OnInit {
todos: Todos[]
constructor(private _todosService: TodosService) {
}
ngOnInit() {
this._todosService.getTodos().subscribe((todos) => {
this.todos = todos;
})
}
onNewTodo(todo: Todos) {
console.log('-- the passed todo --', todo);
this.todos.unshift(todo);
}
}
It tries to emit a newTodo, when a todo is added to db. But it throws the error below:
AppComponent.html:2 ERROR TypeError: _co.onNewTodo is not a function
at Object.eval [as handleEvent] (AppComponent.html:2)
at handleEvent (core.js:10258)
at callWithDebugContext (core.js:11351)
at Object.debugHandleEvent [as handleEvent] (core.js:11054)
at dispatchEvent (core.js:7717)
It looks like a correct implementation. Could anyone let me know what am I doing wrong ? Does it not work with Event Emitter ?
Thanks