2016-12-16 71 views
-1

我有以下項目結構:事件不泡到父組件

enter image description here

todo-form火災created事件,我想在todos組件

待辦事項形式來處理這個事件。 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
待辦事項-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 。:

@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不調用。 此頁面刷新,雖然它不是我的預期。 我錯過了什麼?

+0

@echonax你是什麼意思?在父級導入語句? – gstackoverflow

+0

**從「./todo-form/todo-form.component";**」導入{TodoFormComponent}; – gstackoverflow

+0

我的意思是在你的'@ NgModule'中定義的兩個組件。老實說我找不到任何錯誤,這裏有一個使用'@ Output'的例子:http://plnkr.co/edit/MeQbC7Jbc8rprMF66aEF?p=preview也許它會幫助 – echonax

回答

0

在浪費時間進行調查後,我明白問題出現在輸入錯誤中。

在HTML:

onToDoCreated 

在TS:

onTodoCreated 
0

當你的錯字固定的問題,您的代碼不使用事件冒泡。您仍然在處理組件級別的事件<todo-form>。爲了測試父級上的冒泡,試試這個:

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

div不會得到創建的事件。事件冒泡必須使用本地dom事件來處理。