在我的Angular应用程序中,我有一个父模块与其他子模块一起填充。我的孩子模块有这个模板:
<input type="radio" class="form-control"
[checked] = "message.default == 1"
[value] = "message.default"
(change)="onSelectionChange(message)"
name="default" >
这是ts:
export class MessageComponent implements OnInit {
message: MessageInterface;
@Output() onCheckedChange = new EventEmitter<MessageInterface>();
constructor() { }
ngOnInit() {
}
onSelectionChange(message: MessageInterface) {
this.onCheckedChange.emit(message);
}
}
这是我的父模板
<div #placeholder ></div>
和ts
export class ParentComponent implements OnInit {
@ViewChild('placeholder', {read: ViewContainerRef}) placeHolder;
ngOnInit() {
for(let i=0; i<this.aVariable; i++) {
let factory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
this.placeHolder.createComponent(factory);
}
}
onCheckedChange(message: MessageInterface) {
console.log("parent intercept");
}
其中“aVariable”变量是从我调用的服务返回的值。
当我点击radiobutton时,没有显示日志消息,似乎父节点没有收到EventEmitter发射。 怎么了?
答案 0 :(得分:5)
即使您在运行时创建了这些组件,您仍然需要订阅这些事件!
let comp = this.placeHolder.createComponent(factory) as ComponentRef<ChildComponent>;
// just to be sure, check some things.. :)
if (!comp || !comp.instance || !comp.instance.onCheckedChange) continue;
comp.instance.onCheckedChange.subscribe(msg => this.onCheckedChange(msg));