【发布时间】:2017-01-31 12:30:21
【问题描述】:
我正在尝试从自定义指令接收事件,但它不起作用。我的应用程序中有几个组件可以成功发送事件,所以我做了一个小例子:
<div *appDummyDirective="allTheThings" (dummyOutput)="dummyOuputDirective()">
appDummyDirective
</div>
<appDummyComponent (dummyOutput)="dummyOuputComponent()"></appDummyComponent>
组件的回调被调用,而指令的回调未被调用:
dummyOuputComponent() {
console.log('dummyOuputComponent()'); //gets called
}
dummyOuputDirective() {
console.log('dummyOuputDirective()'); //does not get called!
}
这里是指令和组件的定义。
@Directive({
selector: '[appDummyDirective]'
})
export class DummyDirective{
@Output() dummyOutput = new EventEmitter<any>();
@Input() appDummyDirective: any;
constructor(private viewContainer: ViewContainerRef, private template: TemplateRef<any>) {
this.viewContainer.createEmbeddedView(this.template);
setInterval(any => { this.dummyOutput.emit(null); console.log('fire dummy directive'); }, 1000);
}
}
@Component({
selector: 'appDummyComponent',
template: 'appDummyComponent'
})
export class DummyComponent{
@Output() dummyOutput = new EventEmitter<any>();
constructor() {
setInterval(any => { this.dummyOutput.emit(null); console.log('fire dummy component'); }, 1000);
}
}
我的指令哪里出错了?
【问题讨论】:
-
意味着你不能在指令上使用@Output 装饰器?
-
您确定需要 structural 指令吗?你不能用
appDummyDirective代替*appDummyDirective吗? -
@stj242 如果不能使用
@Output。 -
@AngularFrance:是的,它需要是结构化的,因为我的真实世界指令模仿 ngFor。
-
你得到什么错误?
标签: angular angular2-directives