Search code examples
angulareventemitter

angular2: How to use EventEmitter on components created during runtime?


On my Angular app, i have a parent module populate dinamically with other child modules. My child modules have this template:

<input type="radio" class="form-control"
[checked] = "message.default == 1"
[value] = "message.default"
(change)="onSelectionChange(message)"
name="default" >

and this is ts:

export class MessageComponent implements OnInit {
    message: MessageInterface;
    @Output() onCheckedChange = new EventEmitter<MessageInterface>();

    constructor() { }

    ngOnInit() {
    }  

    onSelectionChange(message: MessageInterface) {
        this.onCheckedChange.emit(message); 
    }
}

and this is my parent template

<div #placeholder  ></div>

and 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");
    }

where "aVariable" variable is a value returned from a service that i invoke.

when i click on a radiobutton, no log message is showed, it seems that parent don't receive EventEmitter emit. What's wrong?


Solution

  • You still need to subscribe to those events, even if you create that component(s) during runtime!

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