I have the following project structure:
todo-form
fires created
event and I want to handle this event in todos
component
todo-form.component.html:
<form class="todo-form" (ngSubmit)="create();" #todoForm="ngForm">
<input name="title" [(ngModel)]="newTodoTitle" type="text" placeholder="Что нужно сделать?" required/>
<button [disabled]="todoForm.form.invalid" type="submit">Добавить</button>
</form>
method create
executes(I see it in debugger )
todo-form.component.ts:
import {Component, Output, EventEmitter} from "@angular/core";
....
@Component({
....
selector: "todo-form",
...
})
export class TodoFormComponent {
@Output() created = new EventEmitter<Todo>();
...
create():void {
if (this.newTodoTitle) {
this.created.emit(new Todo(this.newTodoTitle));
}
}
...
}
todos.component.html:
<todo-form (created)="onToDoCreated($event)"></todo-form>
...
todos.component.ts:
@Component({
moduleId: module.id,
selector: "todos",
templateUrl: "todos.component.html",
styleUrls: ["todos.component.css"]
})
export class TodosComponent implements OnInit {
...
onTodoCreated(todo:ITodo):void {
this.todoService.addTodo(todo).then(todo=>this.addToCache(todo));
}
}
main:
import {BrowserModule} from "@angular/platform-browser";
import {NgModule} from "@angular/core";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component"
import {TodoListComponent} from "./components/todos/todo-list/todo-list.component";
import {TodoListItemComponent} from "./components/todos/todo-list-item/todo-list-item.component";
import {TodoFormComponent} from "./components/todos/todo-form/todo-form.component";
import { InMemoryWebApiModule } from 'angular2-in-memory-web-api';
import { TodoSeedData } from './components/shared/todo.data';
import { TodosComponent } from "./components/todos/todos.component";
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(TodoSeedData)
],
declarations: [AppComponent, TodoListComponent, TodoListItemComponent, TodoFormComponent, TodosComponent],
bootstrap: [AppComponent]
})
export class AppModule {
}
method onTodoCreated
doesn't invoke.
Also page refreshes, athough it is not expected for me.
What did I miss ?
While your typo fixed the problem, your code doesn't use event bubbling. You're still handling the event on the
<todo-form>
component level. For testing bubbling on the parent level try this:The div won't get the created event. Event bubbling has to be handled using native dom events.