Angular 未收到自定义指令的输出
我试图从自定义指令接收事件,但它不起作用。我的应用程序中有几个成功发送事件的组件,因此我举了一个简单的例子:Angular 未收到自定义指令的输出,angular,angular2-directives,Angular,Angular2 Directives,我试图从自定义指令接收事件,但它不起作用。我的应用程序中有几个成功发送事件的组件,因此我举了一个简单的例子: <div *appDummyDirective="allTheThings" (dummyOutput)="dummyOuputDirective()"> appDummyDirective </div> <appDummyComponent (dummyOutput)="dummyOuputComponent()"></appDummy
<div *appDummyDirective="allTheThings" (dummyOutput)="dummyOuputDirective()">
appDummyDirective
</div>
<appDummyComponent (dummyOutput)="dummyOuputComponent()"></appDummyComponent>
以下是指令和组件的定义
@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);
}
}
@指令({
选择器:“[appDummyDirective]”
})
导出类dummy指令{
@Output()dummyOutput=neweventemitter();
@Input()appDummyDirective:任意;
构造函数(私有viewContainer:ViewContainerRef,私有模板:TemplateRef){
this.viewContainer.createEmbeddedView(this.template);
setInterval(any=>{this.dummyOutput.emit(null);console.log('fire dummy directive');},1000);
}
}
@组成部分({
选择器:“appDummyComponent”,
模板:“appDummyComponent”
})
导出类DummyComponent{
@Output()dummyOutput=neweventemitter();
构造函数(){
setInterval(any=>{this.dummyOutput.emit(null);console.log('fire-dummy-component');},1000);
}
}
指令哪里出错了?显然
@Output
与*
的语法糖不兼容
如果您解除指令的语法并将回调绑定应用于模板
元素,那么它就可以工作
<template [appDummyDirective]="allTheThings" (dummyOutput)="dummyOuputDirective()">
<div >
appDummyDirective
</div>
</template>
AppDummy指令
意思是指令上不能有@Output decorators?您确定需要结构指令吗?如果不能使用@Output
@AngularFrance,就不能使用appdummydirection
而不是*appdummydirection
?@stj242:是的,它需要是结构化的,因为我的真实世界指令模仿ngFor。您会遇到什么错误?
<template [appDummyDirective]="allTheThings" (dummyOutput)="dummyOuputDirective()">
<div >
appDummyDirective
</div>
</template>