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?
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With