【问题标题】:angular2 typescript call method on parent from dynamically loaded component来自动态加载的组件的父级的angular2 typescript调用方法
【发布时间】:2017-08-12 17:07:04
【问题描述】:

我正在尝试从动态加载的组件中调用父方法。我正在使用 Angular 食谱https://angular.io/guide/dynamic-component-loader中的动态组件加载器解决方案@

我试图完成的是从加载的组件中调用父级的 deleteBanner 方法。

我在加载的组件(HeroJobAdComponent 和 HeroProfileComponent)上添加了一个 eventEmitter,并尝试在 AdBannerComponent 中捕获事件(deleteBanner)并在 AdBannerComponent 中调用 deleteBanneronParent 上的本地方法。

加载组件中的eventEmitter:

export class HeroProfileComponent implements AdComponent {
  @Input() data: any;
  @Output() deleteBanner: EventEmitter<string> = new 
  EventEmitter<string>();

  removeBanner() {
    console.log('removeBanner on HeroProfileComponent invoked');
    this.deleteBanner.emit(null);
  }
}

并在父级中捕获事件:

<div ad-host (deleteBanner)="deleteBanneronParent()"></div>

已加载组件上的本地方法被调用,但由于某种原因它没有传播到父组件。知道我在这里缺少什么吗?

https://plnkr.co/edit/NzdkaLSEiAmlNnRyN5BW

【问题讨论】:

    标签: angular typescript events


    【解决方案1】:

    由于您使用指令来托管动态组件,因此事件的传播会在指令中丢失,并且父级永远不会收到任何事件。

    您用于将内容插入指令的 loadComponent() 方法已经采用 ComponentRef 并加载内容。您也可以使用此 ComponentRef 来订阅事件。

    为 AdComponent 接口扩展接口:

    import { EventEmitter } from '@angular/core';
    
    export interface AdComponent {
        data: any;
        deleteBanner: EventEmitter<string>;
    }
    

    然后从你的组件订阅事件:

    loadComponent() {
        this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
        let adItem = this.ads[this.currentAddIndex];
    
        let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
    
        let viewContainerRef = this.adHost.viewContainerRef;
        viewContainerRef.clear();
    
        let componentRef = viewContainerRef.createComponent(componentFactory);
        (<AdComponent>componentRef.instance).data = adItem.data;
    
        //Subscribe to the events here 
        (<AdComponent>componentRef.instance).deleteBanner.subscribe(evt => console.log(`Event: ${evt}`));
    }
    

    【讨论】:

    • 感谢@hagner 的洞察力。我没有在文档中找到订阅方法,但我确实在角度源中看到了它。
    • 如果我在 中有动态组件并且我正在使用 @ViewChild() 观看 #dynamic,是否还有其他没有发射器的方法?
    • @Prabesh 您也应该可以直接在 ng-template 中调用您的方法,所以我认为您不需要发射器。但是,如果您无法弄清楚,那么我建议您提出一个单独的问题。
    猜你喜欢
    • 2018-02-25
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多