gpt4 book ai didi

angular - 从组件获取 ViewContainerRef

转载 作者:太空狗 更新时间:2023-10-29 18:15:56 24 4
gpt4 key购买 nike

我想在 Angular 4 中创建嵌套组件

这是选择器组件

import {InputComponent} from './input/input.component'
import {BlockComponent} from './block/block.component'

export const FormChooser = {
Block: BlockComponent,
Input: InputComponent
}

这是组件构建器

const component = FormChooser[data.component]
const factory = this.Resolver.resolveComponentFactory(component)

const new_component = this.ViewContainerRef.createComponent(factory)

如何获取 new_component ViewContainerRef ?所以我可以使用这样的代码

const another_new_component = new_component.createComponent(factory) // as ViewContainerRef

谢谢...

最佳答案

你可以在动态组件的构造函数中注入(inject)ViewContainer

class BlockComponent {
constructor(public vcRef: ViewContainerRef) {}
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent)

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;

或使用 @ViewChild 获取对 ViewContainerRef 的引用

 template: '<ng-container #ref></ng-container>'
})
class BlockComponent {
@ViewChild('ref') vcRef: ViewContainerRef;
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent )

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;

关于angular - 从组件获取 ViewContainerRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44983563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com