事件不会冒泡到父组件

时间:2016-12-16 12:14:54

标签: javascript angular event-handling eventemitter

我有以下项目结构:

enter image description here

todo-form触发created事件,我想在todos组件中处理此事件

待办事项-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>

方法create执行(我在调试器enter image description here中看到它)
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));
    }
}

主要

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 {
}

方法onTodoCreated没有调用。 同时页面刷新,尽管我不希望这样。 我错过了什么?

2 个答案:

答案 0 :(得分:0)

在浪费时间进行调查后,我明白这个问题是错误的。

in html:

onToDoCreated

在ts:

onTodoCreated

答案 1 :(得分:0)

虽然您的拼写错误解决了问题,但您的代码不会使用事件冒泡。您仍然在<todo-form>组件级别处理该事件。要在父级别上测试冒泡,请尝试:

<div (created)="onToDoCreated($event)">
   <todo-form></todo-form>
</div>

div不会获得创建的事件。必须使用本机dom事件处理事件冒泡。