How to call an event in parent component from child component which is loaded using DCL loadintolocation()

后端 未结 2 1690
遇见更好的自我
遇见更好的自我 2020-12-21 02:04

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

2条回答
  •  轮回少年
    2020-12-21 02:36

    update beta.16

    dcl.loadIntoLocation() now needs a ViewContainerRef instead of a template variable name.

    @Component({
        selector: 'dynamic',
        template: `
        

    I'm the dynamic component

    `, }) export class DynamicComponent { someEvent = new EventEmitter(); }
    @Component({
        selector: 'my-app',
        template: `
        

    Hello

    clicked at (top): {{top}}
    dynamic component below
    `, }) 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.

提交回复
热议问题