Reputation: 1596
I have an event in parent component. I want to call that event from the a child component created using DCL loadintolocation()
. I am following this logic in the child component to raise the event
@Output() myevent1: EventEmitter;
onSubmit() {
console.log(this.myForm.value);
this.myevent1.emit();
}
I am able to raise the events for components which are already mentioned but not to components that are created using DCL. Please tell me how to raise the event in parent component from components created dynamically.
Here is the plunker demo i have worked till now http://plnkr.co/edit/2LJL4HxSc74XAyGmQMio?p=preview
Upvotes: 4
Views: 2503
Reputation: 658067
update beta.16
dcl.loadIntoLocation()
now needs a ViewContainerRef
instead of a template variable name.
@Component({
selector: 'dynamic',
template: `
<h1 (click)="null">I'm the dynamic component</h1>
<button (click)="someEvent.emit($event)">click me</button>
`,
})
export class DynamicComponent {
someEvent = new EventEmitter();
}
@Component({
selector: 'my-app',
template: `
<h1>Hello</h1>
<div>
<div>clicked at (top): {{top}}</div>
<span>dynamic component below</span>
<div #target></div>
</div>
`,
})
export class AppComponent {
@ViewChild('target', {read: ViewContainerRef}) target;
top;
constructor(private dcl:DynamicComponentLoader) {}
ngAfterViewInit() {
this.dcl.loadNextToLocation(DynamicComponent, this.target)
.then(ref => {
ref.instance.someEvent
.subscribe(value => {
console.log(value.clientX);
this.top = value.clientX;
console.log(this.top);
})
});
}
}
original
With
loadIntoLocation(
SomeComponent,
someElementRef,
'someAnchor',
[/*other providers, */
provide(ParentComponent, useValue: this)]);
you can pass the parent component to the dynamically created component.
In the child component you just add the parent to the constructor parameter list
constructor(parent: ParentComponent) {}
To not couple parent and child so tightly you can also use a shared service and pass this instead of the parent component itself.
Upvotes: 4
Reputation: 2021
When you load the component, you can subscsribe to the event of the child from where you can call the parent function.
dcl.loadIntoLocation(ChildComponent, elementRef, 'child')
.then((newComponent) => {
newComponent.instance.event.subscribe(() => { .. call your parent ..});
})
UPDATE
see the plunker here: http://plnkr.co/edit/DNmtl6TG5s2dsEUlVTvw?p=preview
Upvotes: 4