如何将组件名称作为参数传递并在函数中接收它

How to pass component name as argument and receive it in function

我需要将组件名称作为参数传递给函数并接收并使用它。但只收到字符串。下面是代码

(click)="this.myapp.openModal('AddContactModelComponent','xl')"

我在这里收到它作为组件使用

 openModal(component:any,size:string) {
    // const modalRef = this.modalService.open(ModalComponent);
    const modalRef = this.modalService.open(
      component,
      {
       size: size, 
      });
      this.modal_title ='test';
  }

传入一个字符串作为 component 参数(在您的示例中为 'AddContactModelComponent')。

您很可能需要一个 openModal 可以像这样使用的映射器

openModal(componentName: string, size: string) {
  const mapper = {
    'AddContactModelComponent': AddContactModelComponent,
    'AnotherString': AnotherComponent,
  };

  const modalRef = this.modalService.open(
    mapper[componentName],
    {
      size: size,
    });
}

然后你可以在你的模板中随意调用它

(click)="this.myapp.openModal('AddContactModelComponent','xl')"