gpt4 book ai didi

Angular 2 : How to use EventEmitter on components created during runtime?

转载 作者:太空狗 更新时间:2023-10-29 17:34:55 25 4
gpt4 key购买 nike

在我的 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”变量是从我调用的服务返回的值。

当我点击单选按钮时,没有显示日志消息,似乎父级没有收到 EventEmitter 发出的消息。怎么了?

最佳答案

即使您在运行时创建该组件,您仍然需要订阅这些事件!

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));

关于 Angular 2 : How to use EventEmitter on components created during runtime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41937278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com