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

后端 未结 2 1688
遇见更好的自我
遇见更好的自我 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: `
        <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.

    0 讨论(0)
  • 2020-12-21 02:51

    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

    0 讨论(0)
提交回复
热议问题