【问题标题】:How to pass component name as argument and receive it in function如何将组件名称作为参数传递并在函数中接收它
【发布时间】:2021-01-05 05:40:57
【问题描述】:

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

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

【问题讨论】:

    标签: angular arguments components


    【解决方案1】:

    正在传递一个字符串作为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')"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多