在Angular中使用动态注入组件时如何访问该函数

时间:2018-03-26 13:50:10

标签: angular

我有一个组件,我动态注入另一个组件。请参考下面的代码:

getID() {
    const componentRef = this.componentFactoryResolver
        .resolveComponentFactory(CodesComponent).create(this.injector);
    componentRef.instance.terms = this.terms;
    this.appRef.attachView(componentRef.hostView);
    const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
        .rootNodes[0] as HTMLElement;
    $(domElem).insertAfter($(event.target).closest('tr'));
}

我的组件中还有一个功能:

sayHello() {
    console.log('hi');
}

我的CodesComponent如下所示:

<p (click) = "sayHello()"></p>

现在的问题是如何从动态创建的组件中调用sayHello()函数?

1 个答案:

答案 0 :(得分:1)

对于您的用例,我建议使用Angulars依赖注入将父组件注入动态组件

这是一个有效的StackBlitz demo

您父组件中的代码

import {
  Component, ViewChild, AfterContentInit, ComponentFactoryResolver,
  Compiler, ViewContainerRef, NgModule, NgModuleRef
} from '@angular/core';


import { BrowserModule } from '@angular/platform-browser';


@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterContentInit {
  @ViewChild('vc', { read: ViewContainerRef }) _container: ViewContainerRef;
  private cmpRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private compiler: Compiler,
    private _m: NgModuleRef<any>) { }

  ngAfterContentInit() {
    this.getID();
  }

  public sayHello(): void{
    alert("Hello!");
  }

  private getID(): void {
    @Component({
      template: `<h2>This is a dynamic component</h2>
      <p (click)="_parent.sayHello()">Click me!</p>`
    })
    class DynamicComponent {
      constructor(public _parent: AppComponent) { }
    }
    @NgModule({
      imports: [
        BrowserModule
      ],
      declarations: [DynamicComponent],
    }) class DynamicModule { }

    const mod = this.compiler.compileModuleAndAllComponentsSync(DynamicModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === DynamicComponent
    );

    this.cmpRef = this._container.createComponent(factory);
  }
}