我想在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
谢谢...
答案 0 :(得分:4)
您可以在动态组件的构造函数中注入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;
答案 1 :(得分:2)
对于Angular +8
import { InputNumberComponent } from '../input-number/input-number.component';
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.scss']
})
export class DynamicFormComponent implements OnInit {
@ViewChild('ref', { read: ViewContainerRef }) vcRef: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) { }
ngOnInit() {
const comp = this.resolver.resolveComponentFactory(InputNumberComponent)
this.vcRef.createComponent(comp)
}
}