【发布时间】:2023-03-09 06:44:01
【问题描述】:
我有一个带有动态创建组件的 App 组件。
父组件有一个<ng-content> 元素,这样我们就可以在父组件中投影我们的子组件。
应用组件:
@Component({
selector: 'my-app',
template:`<ng-container #parentcontainer></ng-container>`,
})
父组件:
@Component({
selector: 'parent',
template: `
<ng-container #container></ng-container>
<ng-content></ng-content>
`
})
子组件:
@Component({
selector: 'child',
template: `<label>
<input type="radio">
</label>
`
})
我的问题是,有什么方法可以访问子组件内的 App 组件的 ViewContainerRef (#parentcontainer) 吗?目标是稍后在#parentcontainer 中动态插入其他组件,例如在子组件中单击某些按钮。
这是StackBlitz 上的工作示例
【问题讨论】:
-
不确定您的任务是什么。如果要传递容器,只需使用数据绑定。但是,如果您想使用容器通过子组件的操作将动态组件插入到父组件中,我不确定这是正确的方法。我只是向上发送一个带有相关数据的事件,然后让父组件添加该组件。