无法从Angular2的EventEmitter捕获事件? [英] Unable to catch events from EventEmitter in Angular2?
问题描述
我已经编写了一个利用EventEmitter类的基本角度应用程序,但是我无法使用侦听组件来捕获事件.
I have written a basic angular application that utilises the EventEmitter class, however i cannot get the listening component to catch the event.
这是我的代码(在Angular2/TypeScript 1.5上使用alpha.27编译为ES5) 对于冗长的示例表示歉意.
Here is my code (using alpha.27 on Angular2 / TypeScript 1.5 compiling to ES5) Apologises for the verbose example.
任何关于我做错了事的建议,将不胜感激.
Any advice on what i am incorrectly doing what would be greatly appreciated.
import {Component, View, EventEmitter} from 'angular2/angular2';
@Component({
selector: 'login',
events : ['loggedIn']
})
@View({
template: '<button type="button" (click)="submitForm()">Click Me</button>'
})
export class Login {
loggedIn = new EventEmitter();
constructor() {
}
submitForm() {
console.log("event fired");
this.loggedIn.next({});
}
}
@Component({
selector: 'app'
})
@View({
template: "<div>This is the application</div>"
})
export class App {
constructor() {
}
}
@Component({
selector: 'root'
})
@View({
template: '<app [hidden]=!showApp></app><login (loggedIn)="loggedIn()" [hidden]=showApp></login>',
directives: [ App, Login ]
})
export class Root {
showApp:boolean;
constructor() {
this.showApp = false;
}
loggedIn() {
console.log("event caught");
this.showApp = true;
}
}
推荐答案
这是正在工作的Plunker 您的应用程序.
import {Component, View, EventEmitter, bootstrap} from '@angular/core';
@Component({
selector: 'login',
events : ['update']
})
@View({
template: '<button type="button" (click)="submitForm()">Login</button>'
})
class Login {
constructor() {
this.update = new EventEmitter();
}
submitForm() {
this.update.next();
}
}
@Component({
selector: 'app'
})
@View({
template: "<div>This is the application</div>"
})
class App {}
@Component({
selector: 'root'
})
@View({
template: `
<app [hidden]="!showApp"></app>
<login (update)="loggedIn()"
[hidden]="showApp"></login>
`,
directives: [App, Login]
})
class Root {
showApp:boolean;
constructor() {
this.showApp = false;
}
loggedIn() {
this.showApp = true;
}
}
bootstrap(Root);
我认为有一些问题.模板中的(update)
是一种事件,因此不能称为loggedIn
.我发现将事件完全称为update
会更容易.
I think there were a few problems. (update)
in the template is a type of event, so it can't be called loggedIn
. I found it easier just to call the event update
altogether.
这篇关于无法从Angular2的EventEmitter捕获事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!