我有以下项目结构:
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
执行(我在调试器中看到它)
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
没有调用。
同时页面刷新,尽管我不希望这样。
我错过了什么?
答案 0 :(得分:0)
在浪费时间进行调查后,我明白这个问题是错误的。
in html:
onToDoCreated
在ts:
onTodoCreated
答案 1 :(得分:0)
虽然您的拼写错误解决了问题,但您的代码不会使用事件冒泡。您仍然在<todo-form>
组件级别处理该事件。要在父级别上测试冒泡,请尝试:
<div (created)="onToDoCreated($event)">
<todo-form></todo-form>
</div>
div不会获得创建的事件。必须使用本机dom事件处理事件冒泡。