Angular 从通用组件调用函数

Angular 从通用组件调用函数,angular,typescript,Angular,Typescript,我使用的是Angular 9,我的数据结构如下: myMap:Map 我的地图中有3个元素,我的值对象的第一个属性是组件类型。我使用它动态创建新组件,如: const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.myMap.get(compName).component); this.container.clear(); const comp = this.container.crea

我使用的是Angular 9,我的数据结构如下:
myMap:Map

我的地图中有3个元素,我的值对象的第一个属性是组件类型。我使用它动态创建新组件,如:

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.myMap.get(compName).component);
this.container.clear();
const comp = this.container.createComponent(componentFactory);
现在我想调用所创建组件的函数。所有组件都有一个共同的功能(例如
foo(string)
),但在每个组件中的实现方式不同。如何调用此函数。 我试着做:
(comp.instance).foo('abcd')
但是我有一个编译错误

我的地图对象的一个示例:

myMap: Map<key: string, value: {component: any, data: string}> = [
    ['compA', {comp: AComponent, data: 'A'}],
    ['compB', {comp: BComponent, data: 'B'}],
    ['compC', {comp: CComponent, data: 'C'}]
]
myMap:Map=[
['compA',{comp:A组件,数据:'A'}],
['compB',{comp:B组件,数据:'B'}],
['compC',{comp:CComponent,数据:'C'}]
]
我想到的方法是使用3条if-else语句,如:

if (compName === 'compA') {
    (<compA>comp.instance).foo('abcd');
} else if (compName === 'compB') {
    (<compB>comp.instance).foo('abcd');
} else if (compName === 'compC') {
    (<compC>comp.instance).foo('abcd');
}
if(compName==“compA”){
(comp.instance).foo('abcd');
}else if(compName=='compB'){
(comp.instance).foo('abcd');
}else if(compName=='compC'){
(comp.instance).foo('abcd');
}
但这真的不漂亮,还有别的方法吗

  • 使用
    foo
    函数定义一个接口:
  • 在组件中实现此接口:
  • 使用组件的窄类型更新
    myMap
  • 类型MyMap=Map;
    
    现在

    • this.myMap.get(compName).component的类型为
      type
    • componentFactory
      具有类型
      componentFactory
    • comp
      具有类型
      ComponentRef
    • 最后,
      comp.instance
      具有类型
      WithFoo
      ——因此您可以在其上调用
      .foo(数据)
    interface WithFoo {
      foo: (s: string): void
    }
    
    @Component()
    class CompA implements WithFoo {
      foo(s: string): void {...} 
    }
    
    type MyMap = Map<string, {component: Type<WithFoo>, data: string}>;