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 t
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);
})
});
}
}
Plunker example beta.17
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.
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