【问题标题】:Pass Component Name from HTML to Component将组件名称从 HTML 传递给组件
【发布时间】:2019-02-23 17:02:25
【问题描述】:

有一种情况,我想让我的 Refactor 成为我的 Angular 应用程序。

我有一个 html,在单击不同按钮时,我想打开对话框,除了单击按钮时打开的组件外,其他所有方面都相同。

<button mat-raised-button (click)="openDialog('ComponentA')">Component A</button> <button mat-raised-button (click)="openDialog('ComponentB')">Component B</button> <button mat-raised-button (click)="openDialog('ComponentC')">Component C</button> <button mat-raised-button (click)="openDialog('ComponentD')">Component D</button>

单击按钮时,我调用 openDialog ,它依次打开对话框,其结构取决于传递的组件。

openDialog(component){
 const dialogRef = this.dialog.open(component, {
  width: '250px',
  data: {name: this.name, animal: this.animal}
});

}

但是,当我在 openDialog 中控制台组件时,我的组件名称显示为一个简单的字符串,而不是完整的组件结构。

我已经在 app.module 的入口组件中添加了我的组件。

如果我正在尝试的实现是可能的,请告诉我。

提前致谢。

【问题讨论】:

    标签: javascript typescript angular6


    【解决方案1】:

    它显示为一个字符串,因为 'ComponentA' 指的是一个字符串。您将导入并将组件构造函数传递给您的对话框。然后在你的对话框组件中,注入ComponentFactoryResolver服务和ViewContainerRef来初始化组件:

    举例

    parent.component.ts

    import { ComponentA } from './component-a.component.ts';
    import { ComponentB } from './component-b.component.ts';
    
    class ParentComponent {
      public ComponentA = ComponentA;
      public ComponentB = ComponentB;
    
      @ViewChild('dialog') dialog;
    }
    
    

    parent.component.html

    <button mat-raised-button (click)="dialog.openDialog(ComponentA)">Component A</button>
    <button mat-raised-button (click)="dialog.openDialog(ComponentB)">Component B</button>
    

    dialog-box.component.ts

    class DialogBoxComponent {
      constructor(private viewRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {
      }
    
      openDialog(componentConstructor) {
        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentConstructor);
        const componentInstance = this.viewContainerRef.createComponent(componentFactory);
        // add any initialisation you might need to do to componentInstance
      }
    
    }
    

    请注意,以这种方式创建的组件不会让它们的 @Input() 和 @Output() 装饰器工作。这是 Angular 编译器的一个限制,它在设计上偏向于单态组件。

    因此,您必须手动设置依赖于@Input() 的子组件的属性。对于@Output(),您必须手动订阅组件上的任何事件侦听器。

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 2020-02-04
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多