Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 550
giozh Avatar asked Jan 30 '17 13:01

giozh


People also ask

Can we use EventEmitter in a service?

Event-emitter is imported from “@anguar/core” package. It is used in directives and components to emit custom events synchronously or asynchronously and register handlers for those events by subscribing to an instance. Event emitter is a generic type, it can take any additional information.

How do I use EventEmitter?

Step 1: Import output and EventEmitter from angular/core in your ts file. Step 2: Add a property with @Output decorator which has a type of EventEmitter. Step 3:Create an add method in the same component ts file So, your ts file will look like this: Child. component.

How do you pass two arguments in EventEmitter?

For passing the parameters, we will wrap all the parameters inside the curly brackets (this will combine them as a single object) and pass it to the emit method. To receive the parameters in the parent component, we will make a similar type of object and update its value with that of the received object.


1 Answers

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));
like image 150
slaesh Avatar answered Sep 19 '22 02:09

slaesh