【问题标题】:Angular 2 dynamic loaded component, events not firing back?Angular 2动态加载的组件,事件没有回火?
【发布时间】:2016-04-05 20:35:29
【问题描述】:

我使用了 Angular2 动态组件加载器。一切正常。

我的动态加载的组件发出事件,但我无法在任何地方捕获它。

父代码:

this.dcl.loadAsRoot(SomeComponent, "#dynamiccomponenthere", this.injector)

父模板:

<div id="dynamiccomponenthere" (somecustomevent)="someFunc()"></div>

孩子:

...
this.somecustomevent.emit(data)
...

*解决方案:(感谢 Gunther)*

cmp.instance['somecustomevent'].subscribe(ev => {
    this.consoleLog(ev) // run function in parent!
})

【问题讨论】:

    标签: typescript angular


    【解决方案1】:
    • Lo​​adAsRoot 不调用更改检测

    目前loadAsRoot() 仅用于引导根组件 (AppComponent),根组件不支持输入。

    此评论中解释了解决方法https://github.com/angular/angular/issues/6370#issuecomment-193896657

    使用 loadAsRoot 时,您需要触发更改检测并手动连接 Inputs、Outputs、Injector 和组件处置功能

    function onYourComponentDispose() {
    }
    let el = this.elementRef
    let reuseInjectorOrCreateNewOne = this.injector;
    this.componentLoader.loadAsRoot(YourComponent, this.elementRef, reuseInjectorOrCreateNewOne, onYourComponentDispose)
    .then((compRef: ComponentRef) => {
      // manually include Inputs
      compRef.instance['myInputValue'] = {res: 'randomDataFromParent'};
      // manually include Outputs
      compRef.instance['myOutputValue'].subscribe(this.parentObserver)
      // trigger change detection
      cmpRef.location.internalElement.parentView.changeDetector.ref.detectChanges()
      // always return in a promise
      return compRef
    });
    

    另见@ContentChild is null for DynamicComponentLoader

    【讨论】:

    • 查看myOutputValue 所在的行。这是一个如何为使用loadAsRoot() 添加的组件设置事件监听的示例。
    • 在这个例子中。 this.parentObserver 应该是什么? parentObserver 来自哪里?
    • 没关系..我想通了。 parentObserver 在我的情况下它是一个内部函数.. IE private someFunction(){ }
    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 2017-04-05
    • 1970-01-01
    • 2017-12-15
    • 2019-10-19
    • 1970-01-01
    • 2018-02-02
    • 2017-10-21
    相关资源
    最近更新 更多