Problems with Dynamic components Angular 12

Viewed 279

i have problems with integration of dynamic components in angular 12, there is a delay when i click on box and when the box appear.

steps

click one time on the button Box nothing happen and click an other time on the button Box, a div appear, it's the div when you clicked the first time on the button


(and when i click an other time, i have an error "_a.clear() is not a function".) (checked)


Can you help me ?

DEMO

2 Answers

It's a type issue. You have @ViewChildren('container') items!: QueryList<ViewContainerRef>;, but @ViewChildren is in fact a QueryList of type ElementRef in your case.

What you need to do is to tell Angular that you want the ViewContainerRef and not the ElementRef. To do so, add the read parameter:

@ViewChildren('container', { read: ViewContainerRef }) items!: QueryList<ViewContainerRef>;

For more details, you can check Angular's docs.

Apart from the the other answer, kindly referring to that:

@ViewChildren('container', { read: ViewContainerRef }) items!: QueryList<ViewContainerRef>;

The delay is caused by a race condition, when you call onChanges, angular hasn't had time to run change detection, so you are one step behind. You could wrap calling the function inside a setTimeout, it would do, or you can manually run change detection after you have inserted/deleted the component. So for that, import ChangeDetectorRef, inject it into the constructor and call detectChanges:

constructor(
  public sanitizer: DomSanitizer,
  private resolver: ComponentFactoryResolver,
  private cdr: ChangeDetectorRef
) {}

addComponent(index: number) {
  if (index === 0) {
    this.Components.push(ResizableDraggableComponent);
  }
  this.cdr.detectChanges(); // <<<<<<<<<<<<<<< Trigger change detection
  this.onChanges();
}

Your forked STACKBLITZ

Related