Web Developer

Section 21 Dynamic Component

Recommend to use *ngIf to control the components already created

However, you still can use programmatically create component, you have to

  1. create a component as type for the component factory
  2. using ComponentFactoryResolver.resolveComponentFactory(component type – first step export class) to create a component factory (the argument is the component you have already create)
  3. 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
  4. 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)
  5. then in this host DOM to create dynamic component, using .createComponent(componentFactory).
  6. 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

Next Article