【问题标题】:Angular: How to use a component dynamically in another component?Angular:如何在另一个组件中动态使用一个组件?
【发布时间】:2023-02-10 16:16:52
【问题描述】:

我有一个用于 Angular Material 的 DialogService:

constructor(private dialog: MatDialog){}

openDialog(dialogData){
        const dialogRef = this.dialog.open(DialogComponent, {
                data: dialogData
       }
}

和一个 DialogComponent 来打开对话框:

let componentToRender

constructor(@Inject(MAT_DIALOG_DATA) public dialogData){
       this.componentToRender = dialogdata.componentToRender
}

和这个模板:

<div class="dialog">
        <ng-container></ng-container> // Here i want to dynamically render a given component
</div>

我想给我的 dialogService 和 dialogData 一个组件的引用,我想在我的 diaologComponent &lt;ng-container&gt; 中呈现

结果应该是,我可以调用我的服务并引用一个组件来打开一个对话框容器,该容器在 component.html 的 ng-container 中呈现这个给定的组件。例如像这样:

let dialogData = {}

dialogData.componentToRender = COMPONENT_TO_RENDER_INSIDE_OF_DIALOG

this.dialogService.openDialog(dialogData)

我的想法是制作类似对话框容器的东西,其中主体可以是我想在对话框容器内呈现的任何组件

我希望只写必要的代码就足够了,因为我是从另一台电脑上问这个问题的,无法复制粘贴我已有的东西。谢谢 :)

【问题讨论】:

  • 路由器插座呢?
  • router-outlet 对我没有帮助,因为对话框没有路径。但我想在我的 dialogComponent.html 中创建类似路由器插座的东西

标签: javascript angular angular-material


【解决方案1】:

现在我用 ViewContainerRef 解决了这个问题。 我使用 createComponent() 方法并给它我想要渲染的组件。 然后我将 create ref 插入到我的 ng-template 中。

@ViewChild('container', {read: ViewContainerRef}) container!: ViewContainerRef

const componentRef = this.viewContainerRef.createComponent(MY_COMPONENT_DYNAMICALLY_GIVEN)
this.container.insert(componentRef.hostView)

这有效,但也会在我的内容周围呈现我的组件选择器标签。

<my_inserted_component> <!-- I need to get rid of this :D -->
       <!-- contents of my_inserted_component -->
</my_inserted_component>

可悲的是,这会导致布局问题。所以现在我需要找出如何更改我的 CSS 或(更好)如何摆脱带有组件选择器名称的外部标签。

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 1970-01-01
    • 2019-12-08
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多