我使用Angular 2 quickstart设置了我的项目。然后我有以下组件,尝试遵循类似的模式as here:
main.ts:
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
bootstrap(AppComponent);
app.component.ts:
import { Component } from '@angular/core';
import { MenuComponent } from './menu.component';
@Component({
selector: 'my-app',
template: `<menu (onToggleEvent)="onToggle($event)"></menu>`,
directives: [ MenuComponent ]
})
export class AppComponent {
onToggle(data) {
console.log(data);
}
}
menu.component.ts:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'menu',
template: `<button (click)="toggleMe()">Toggle Me</button>`
})
export class MenuComponent {
@Output onToggleEvent = new EventEmitter();
public toggleMe(): void {
this.onToggleEvent.emit('test');
}
}
的index.html:
<html>
<head>
<title>My page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
当我调试时,toggleMe()
执行并发出事件,但永远不会调用onToggle()
方法。有什么想法吗?
答案 0 :(得分:4)
发现错误 - @Output
注释旁边没有括号。我使用Angular QuickStart中包含的简单服务器,它使用BrowserSync和TypeScript观察器来实时传输。仅以某种方式添加@Output
而不是@Output()
从未被转录器捕获,而且这是默默无效的。在我停止服务器并尝试重新启动它(启动转换)后,错误被抛出,这让我陷入了错误。