0

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

Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54

1 Answers1

1

According to your example, you've defined this template <app-todoinput (newTodo)="onNewTodo($event)"> in your AppComponent's HTML. While your onNewTodo($event) is a part of todolist.component.ts. Thus the error.

What you should be doing instead is, since you want to change data between two sibling components, you should be implementing a service with a BehaviorSubject, instead of an Output property in the child component.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110