angular2:如何在运行时创建的组件上使用 EventEmitter?
angular2: How to use EventEmitter on components created during runtime?
在我的 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 应用程序中,我有一个父模块动态填充了其他子模块。我的子模块有这个模板:
<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));