我有以下項目結構:事件不泡到父組件
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
執行(我看到它在調試器)
待辦事項-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
不調用。 此頁面刷新,雖然它不是我的預期。 我錯過了什麼?
@echonax你是什麼意思?在父級導入語句? – gstackoverflow
**從「./todo-form/todo-form.component";**」導入{TodoFormComponent}; – gstackoverflow
我的意思是在你的'@ NgModule'中定義的兩個組件。老實說我找不到任何錯誤,這裏有一個使用'@ Output'的例子:http://plnkr.co/edit/MeQbC7Jbc8rprMF66aEF?p=preview也許它會幫助 – echonax