0

What's wrong with that code:

  @Directive({
  selector: '[appDir]'
})
export class DirDirective {

  constructor(
    private vcr: ViewContainerRef,
    private compFactoryResolver: ComponentFactoryResolver
  ) {}
  ngAfterViewInit() {
    const compAFactory = this.compFactoryResolver.resolveComponentFactory(
      CompAComponent
    );
    const compBFactory = this.compFactoryResolver.resolveComponentFactory(
      CompBComponent
    );

    const compARef = this.vcr.createComponent(compAFactory);

    this.vcr.createComponent(compBFactory, 0, undefined, [
      [compARef.location.nativeElement]
    ]);
  }
}

Only fails when IVY is enable

https://stackblitz.com/edit/angular-h3wqc4?file=src%2Fapp%2Fdir.directive.ts

IsraGab
  • 4,819
  • 3
  • 27
  • 46
  • what is the end goal? – profanis Dec 18 '20 at 10:08
  • I would like to use a directive instead of a component. As the code shows, the directive should create 2 components (dynamically) and insert one of the component into the other using projectableNodes – IsraGab Dec 18 '20 at 10:14

1 Answers1

0

I had this problem and this was how I solved it:

1st - add Injector (from @angular/core) to the constructor

constructor(private vcr: ViewContainerRef,
private compFactoryResolver: ComponentFactoryResolver,
private injector: Injector) {}

2nd - replace this line of code

const compARef = this.vcr.createComponent(compAFactory);

with the following code

const compARef = compAFactory.create(this.injector);

And just a side note: in my project I don't have the ViewContainerRef on the constructor, it's assigned with ViewChild

@ViewChild('target', { read: ViewContainerRef })
    private vcr: ViewContainerRef;
<ng-container #target></ng-container>

So if you're having any problem you can try that.

Alex
  • 11
  • 2