在Angular中使用动态注入组件时如何访问函数 [英] How to access the function when using dynamic injecting component in Angular

查看:276
本文介绍了在Angular中使用动态注入组件时如何访问函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要动态注入另一个组件的组件.请参考下面显示的代码:

I have a component where I am dynamically injecting another component. Please refer the code shown below:

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'));
}

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

Also there is a function in my component:

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

我的CodesComponent如下所示:

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

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

Now question is how can I call sayHello() function from dynamically created component?

推荐答案

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

For your use case I would recommend using Angulars dependency injection to inject the parent component into your dynamic component.

这是为您工作的 StackBlitz演示.

父组件中的代码

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);
  }
}

这篇关于在Angular中使用动态注入组件时如何访问函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆