Recommend to use *ngIf to control the components already created
However, you still can use programmatically create component, you have to
- create a component as type for the component factory
- using ComponentFactoryResolver.resolveComponentFactory(component type – first step export class) to create a component factory (the argument is the component you have already create)
- create a helper Directive, such as PlaceholderDirective, in this directive constructor, set up ViewContainerRef as public, which will be used to access the host DOM of this directive
- Using @ViewChild(PlaceholderDirective(note: this is class name)) to access this directive, and then, using this referenced directive’s viewContainerRef to access it host DOM (step 3)
- then in this host DOM to create dynamic component, using .createComponent(componentFactory).
- to binding data of this dynamic component, using .instance to access this dynamic component, for EventEmitter, using subscribe() to monitor.
ViewContainerRef, ElementRef, TemplateRef, ViewRef: https://zhuanlan.zhihu.com/p/56224354